Python:制作字典,将文件夹名称作为键,文件名作为值



我想制作一个字典,将文件夹名称作为键,文件名作为值 对于不同文件夹中的不同文件。下面是我实现这一点的代码,但我没有得到预期的输出。

我有一个目录,其中存在不同的文件夹。目录名是sreekanth,里面有许多文件夹,如AA1A2A3,其中包含.csv文件。
我正在尝试从不同的文件夹中收集所有.csv文件,并将它们分配给 Python 字典中的相应文件夹。

from os.path import os
import fnmatch
d={}
l = []
file_list = []
file_list1 = []
for path,dirs,files in os.walk('/Users/amabbu/Desktop/sreekanth'):
for f in fnmatch.filter(files,'*.csv'):
if os.path.basename(path) in d.keys():
file_list.append(f)
d = {os.path.basename(path):list(file_list)}
print("First",d)
else:
d.setdefault(os.path.basename(path),f)
print("Second",d)

以下是使用defaultdict模块执行所需操作的更简单方法:

import os
import fnmatch
from collections import defaultdict

d=defaultdict(set)
for path,dirs,files in os.walk('/Users/amabbu/Desktop/sreekanth'):
for f in fnmatch.filter(files,'*.csv'):
d[os.path.basename(path)].add(f)
print(dict(d))

相关内容

最新更新