Sreekanth A
Sreekanth A

Reputation: 9

Python: Make dictionary with folder names as key and file names as values

I want to make a dictionary with folder names as key and file names as values for different files in different folders. Below is my code to achieve that, but I am not getting the expected output.

I have a directory within that different folders are present. The directory name is sreekanth, within are many folders like A, A1, A2, A3, which contain .csv files.
I am trying to collect all the .csv files from the different folders and assigning them to the corresponding folder in a Python dictionary.

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)

Upvotes: 1

Views: 1890

Answers (1)

Anwarvic
Anwarvic

Reputation: 12992

The following is a simpler way to do what you want using defaultdict module:

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))

Upvotes: 2

Related Questions