Python:从字典的嵌套列表中创建目录树 [英] Python: Create directory tree from nested list of dictionaries

查看:148
本文介绍了Python:从字典的嵌套列表中创建目录树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从下面的python词典列表中创建目录树?子目录级别的数量必须是可变的.

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

我想用python完成类似以下任务的事情:

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

  • 遍历1级键
    • 使用键名创建文件夹
    • 如果其值不是''
      • 创建子文件夹
      • 如果子文件夹的值不是''
        • 创建子文件夹...
        • ...等等,直到没有更深的层次为止,
        • 然后转到下一个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)
        

        createPath(dirTree) createPath(dirTree,"/some/where)之类的调用来选择初始开始

        Call like createPath(dirTree) or createPath(dirTree, "/some/where) to choose the initial start

        仅包含 dict 的简单结构会更有用,因为仅用于一个映射的dict不太好

        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)
        

        这篇关于Python:从字典的嵌套列表中创建目录树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆