Python: Create Directory Tree From Nested List Of Dictionaries
How can I create a directory tree from the below list of dictionaries in python? The number of subdirectory levels has to be variable. dirTree: [{'level-1_dir-1': ''}, {'
Solution 1:
You may recursivly create the dir, with the appropriate way regarding your structure
def createPath(values, prefix=""):
for item in values:
directory, paths = list(item.items())[0]
dir_path = join(prefix, directory)
makedirs(dir_path, exist_ok=True)
createPath(paths, dir_path)
Call like createPath(dirTree)
or createPath(dirTree, "/some/where)
to choose the initial start
A simplier structure with only dicts
would be more usable, because a dict for one mapping only is not very nice
res = {
'level-1_dir-1': '',
'level-1_dir-2':
{
'level-2_dir-1':
{
'level-3_dir-1': '',
'level-3_dir-2': '',
'level-3_dir-3': ''
},
'level-2_dir-2': ''
},
'level-1_dir-3': '',
'level-1_dir-4': ''
}
# with appropriate code
def createPath(values, prefix=""):
for directory, paths in values.items():
dir_path = join(prefix, directory)
makedirs(dir_path, exist_ok=True)
if isinstance(paths, dict):
createPath(paths, dir_path)
Post a Comment for "Python: Create Directory Tree From Nested List Of Dictionaries"