函数从目录中顺序打开大量文件是如何实现的?
我不想写:
file name =
'C:\\Users\\erjan\\PycharmProjects\\STRUCT\\rtv.txt',
'C:\\Users\\erjn\\PycharmProjects\\STRUCT\\pip.txt',
'C:\\Users\\erjn\\PycharmProjects\\STRUCT\\3re4.txt',
'C:\\Users\\erjn\\PycharmProjects\\STRUCT\\...'
我想将
path: "C:\\Users\\erjn\\PycharmProjects\\STRUCT"
放入变量中并将计数器设置为 +11,但我应该写什么呢?
搜索没有结果。
folder_path = '/path/to/your/folder'
# Check if the folder path exists
if os.path.exists(folder_path) and os.path.isdir(folder_path):
# Get the list of files in the folder
file_list = os.listdir(folder_path)
# Loop through the files and open them
for file_name in file_list:
# Construct the full path to the file
file_path = os.path.join(folder_path, file_name)
# Check if the item is a file (not a subdirectory)
if os.path.isfile(file_path):
try:
with open(file_path, 'r') as file:
# Your code to process or read the file goes here
print(f"Processing file: {file_name}")
content = file.read()
# Process content as needed
except Exception as e:
print(f"Error processing file {file_name}: {e}")```