在以上代码的基础上,可以使用sorted()函数来按文件名顺序打开文件:

file_list = sorted(os.listdir(os.path.join(dir_path, folder)))  # 获取文件列表并按文件名排序

for txt_file in file_list:
    if not txt_file.endswith('.pci'):
        continue

    file_path = os.path.join(dir_path, folder, txt_file)

    with open(file_path, 'rb') as f:
        # 处理文件内容

通过使用sorted()函数,可以将文件列表按文件名的字母顺序排序,然后遍历文件列表,打开并处理每个pci文件。

我需要按文件名顺序来打开 for txt_file in oslistdirospathjoindir_path folder if not txt_fileendswithpci # 如果该文件不是pci文件则跳过 continue file_path = ospathjoindir_path folder txt_file # 拼接出pci文件的全路径 # 打开pci文件并读取内容 with openfile_path rb as f

原文地址: https://www.cveoy.top/t/topic/Cos 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录