Python: Create directory tree from nested list of dictionaries

你离开我真会死。 提交于 2021-01-29 05:29:24

问题


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': ''}, 
    {'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': ''}
    ]

I would like to accomplish something like the following tasks with python:

  • Iterate through the level-1 keys
    • create folder with key name
    • if it has a value other than ' '
      • create subfolder
      • if the subfolder has a value other than ' '
        • create subfolder...
        • ...and so on, until there are no more deeper levels,
        • then go to the next level-1 key and start over

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


来源:https://stackoverflow.com/questions/62523528/python-create-directory-tree-from-nested-list-of-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!