连续打开1000个文本文件

问题描述 投票:0回答:1

函数从目录中顺序打开大量文件是如何实现的?

我不想写:

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,但我应该写什么呢?

搜索没有结果。

python
1个回答
0
投票

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}")```
© www.soinside.com 2019 - 2024. All rights reserved.