Py学习  »  Python

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

swordfish • 6 年前 • 1951 次点击  

我想解决一个问题,但有点困惑。

我要做的是创建一个dictionary对象,该对象包含目录文件夹及其文件 儿童 ,就像这个:

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"
                        }
                    ]
                }
            ]
        }
    ]
}

我在这里得到的代码只是dirname和文件名,它们作为键和值分配给dictionary:

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48819
文章 [ 1 ]  |  最新文章 6 年前
Sam
Reply   •   1 楼
Sam    6 年前

试试附加的代码。它不包括您指定的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