How to open concurrently two files with same name and different extension in python?
我有一个文件夹,其中包含多个文件:
1 2 3 4 5 | a.txt a.json b.txt b.json |
等等:
使用for循环,我想同时打开两个文件(a.txt和a.json)。
有没有一种方法可以使用Python中的"with"语句来完成它?
您可以执行如下操作:构造一个以文件名sans扩展名为键的字典,并计算与所需扩展名匹配的文件数。然后您可以迭代字典打开的文件对:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import os from collections import defaultdict EXTENSIONS = {'.json', '.txt'} directory = '/path/to/your/files' grouped_files = defaultdict(int) for f in os.listdir(directory): name, ext = os.path.splitext(os.path.join(directory, f)) if ext in EXTENSIONS: grouped_files[name] += 1 for name in grouped_files: if grouped_files[name] == len(EXTENSIONS): with open('{}.txt'.format(name)) as txt_file, \ open('{}.json'.format(name)) as json_file: # process files print(txt_file, json_file) |