Python-从文件夹目录创建字典

标签 python python-3.x

我正在尝试解决一个问题,但有点令人困惑。

我想要做的是创建一个字典对象,其中包含目录文件夹及其文件作为,如下所示:

vm.folder = {
    id: 'root',
    name: 'Root',
    type: "folder",
    children: [
        {
            id: "Folder 1",
            name: "1",
            type: "folder",
            children: [
                {
                    id: "Folder 1a",
                    name: "1a",
                    type: "folder",
                    children: [
                        {
                            id: "1a1",
                            name: "1a1",
                            type: "file"
                        },
                        {
                            id: "1a2",
                            name: "1a2",
                            type: "file"
                        }
                    ]
                }
            ]
        }
    ]
}

我这里的代码只是获取目录名和文件名,将它们作为键和值分配给字典:

def pathto_dict(path):
    file_token = ''
    for root, dirs, files in os.walk(path):
        tree = {dir: pathto_dict(os.path.join(root, dir)) for dir in dirs}
        tree.update({file: file_token for file in files})
        return tree

最佳答案

尝试附加的代码。它不包含您指定的 id 属性,但可以轻松地将其添加到代码的 tree = {} 部分中。

def pathto_dict(path):
    for root, dirs, files in os.walk(path_):
        tree = {"name": root, "type":"folder", "children":[]}
        tree["children"].extend([pathto_dict(os.path.join(root, d)) for d in dirs])
        tree["children"].extend([{"name":os.path.join(root, f), "type":"file"} for f in files])
        return tree

关于Python-从文件夹目录创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58702587/

相关文章:

python - Django Rest Framework 不序列化 SerializerMethodField

python - 在 1 年的时间跨度内有效地分发大量事件

Python Datetime 将 timedelta 舍入到最近的最大单位

python - 等同列表如何工作? -可变的基本概念

python - 将多态对象从 C++ 传递给 python 函数

javascript - 如何通过http正确发送二进制文件并使用javascript下载它?

python - Pandas 处理 numpy timedelta64[ms]

python - python 3相当于1000000000L是多少

python - 在 Python 中,我应该在 if block 中返回后使用 else 吗?

python - 如何使用 wxPython 创建具有 alpha channel 透明度的窗口?