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

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

我想制作一个以文件夹名作为键,文件名作为值的字典用于不同文件夹中的不同文件。下面是我的代码以实现该目标,但未获得预期的输出。

我的目录中存在不同的文件夹。目录名称为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)
python dictionary
1个回答
0
投票

以下是使用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))
© www.soinside.com 2019 - 2024. All rights reserved.