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

我正在尝试解决一个问题,但有些混乱。

我想做的是创建一个字典对象,其中包含一个目录文件夹及其作为孩子的文件,就像这样:

vm.folder = {
    id: 'root',name: 'Root',type: "folder",children: [
        {
            id: "Folder 1",name: "1",children: [
                {
                    id: "Folder 1a",name: "1a",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
jed_yu 回答:Python-从文件夹目录创建字典

尝试附加的代码。它不包含您指定的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
本文链接:https://www.f2er.com/3163116.html

大家都在问