I am trying to store directory structure in a nested dictionary. The tree of the directory
├── dirA
│ ├── dirB1
│ │ └── file1.txt
│ └── dirB2
│ └── file2.txt
├── templates
│ ├── base.html
│ └── report.html
└── test.py
The nested dictionary is like:
{'dirs': {'.': {'dirs': {'dirA': {'dirs': {'dirB1': {'dirs': {},
'files': ['file1.txt']},
'dirB2': {'dirs': {},
'files':['file2.txt']}
}
'files': []},
'templates':{'dirs':{},
'files':['base.html', 'report.html']}},
'files': ['test.py']}},
'files': []}
I think recursion is a good way to do this.
import os
import pprint
pp = pprint.PrettyPrinter()
def path_to_dict(path):
d = {'dirs':{},'files':[]}
name = os.path.basename(path)
if os.path.isdir(path):
if name not in d['dirs']:
d['dirs'][name] = {'dirs':{},'files':[]}
for x in os.listdir(path):
d['dirs'][name]= path_to_dict(os.path.join(path,x))
else:
d['files'].append(name)
return d
mydict = path_to_dict('.')
pp.pprint(mydict)
The result is different from what I expected. But I don't know which step goes wrong in the recursion.
d = {'dirs':{},'files':[]}will reset the dictionary items.os.walk()is usually much easier to work with when traversing directory structures.os.walk()can go through the directory. But I am trying to stroe the directory structure.