我有一个包含多个文件的文件夹:
a.txt
a.json
b.txt
b.json
等等:
使用for循环我想同时打开几个文件(a.txt和a.json)。
有没有办法使用'和'在python中的语句?
答案 0 :(得分:1)
您可以执行以下操作,构建由文件名sans扩展名键入的字典,并计算与所需扩展名匹配的文件数。然后你可以遍历字典打开文件对:
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)
答案 1 :(得分:0)
我有两个不同文件的文件夹,一个是 .jpg,另一个是 .xml,这就是我将它们放入另一个文件夹的方式
import os
from pathlib import Path
import shutil
#making the list to store the name
picList=list()
xmlList=list()
#making the directory path
xmlDir = os.listdir('C:\\Users\\%USERNAME%\\Desktop\\img+xml\\XML')
picDir=os.listdir('C:\\Users\\%USERNAME%\\Desktop\\img+xml\\img')
dest=r'C:\Users\%USERNAME%\Desktop\img+xml\i'
#appending the file name to the list
for a in xmlDir:
a=Path(a).stem
xmlList.append(a)
picList.append(a)
#matching and putting file name in destination
for a in xmlList:
for b in picList:
if a==b:
try:
shutil.move(f'C:\\Users\\%USERNAME%\\Desktop\\img+xml\\XML\\{a}.xml',dest)
shutil.move(f'C:\\Users\\%USERNAME%\\Desktop\\img+xml\\img\\{b}.jpg',dest)
except Exception as e:
print(e)