在Python中识别文件系统中的根文件夹

时间:2019-05-21 16:30:12

标签: python

我有一个遍历文件系统结构并从中创建字典的递归方法。 这是代码:

def path_to_dict(path):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):        
        d['type'] = "directory"
        d['path'] = os.path.relpath(path).strip('..\\').replace('\\','/')
        d['children'] = [path_to_dict(os.path.join(path, x)) for x in os.listdir\
(path)]
    else:
        d['type'] = "file"
        d['path'] = os.path.relpath(path).strip('..\\').replace('\\','/')
        with open(path, 'r', encoding="utf-8", errors='ignore') as myfile:
            content = myfile.read().splitlines()
        d['content'] = content

此刻,它检查它是否是文件夹,然后放置键nametypepathchildren,其中children是数组其中可以包含其他文件夹或文件。如果是文件,则具有键nametypepathcontent。 将其转换为JSON后,最终结构如下。

{
    "name": "nw",
    "type": "directory",
    "path": "Parsing/nw",
    "children": [{
        "name": "New folder",
        "type": "directory",
        "path": "Parsing/nw/New folder",
        "children": [{
            "name": "abc",
            "type": "directory",
            "path": "Parsing/nw/New folder/abc",
            "children": [{
                "name": "text2.txt",
                "type": "file",
                "path": "Parsing/nw/New folder/abc/text2.txt",
                "content": ["abc", "def", "dfg"]
            }]
        }, {
            "name": "text2.txt",
            "type": "file",
            "path": "Parsing/nw/New folder/text2.txt",
            "content": ["abc", "def", "dfg"]
        }]
    }, {
        "name": "text1.txt",
        "type": "file",
        "path": "Parsing/nw/text1.txt",
        "content": ["aaa "]
    }, {
        "name": "text2.txt",
        "type": "file",
        "path": "Parsing/nw/text2.txt",
        "content": []
    }]

}

现在,我希望脚本始终将仅根文件夹中的type设置为值root。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

我认为您想要的东西与以下实现类似。根文件夹中的目录和文件将包含"type": "root",子元素将不包含此键值对。

def path_to_dict(path, child=False):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):
        if not child:
            d['type'] = "root"
        d['path'] = os.path.relpath(path).strip('..\\').replace('\\','/')
        d['children'] = [path_to_dict(os.path.join(path, x), child=True) for x in os.listdir\
(path)]
    else:
        if not child:
            d['type'] = "root"
        d['path'] = os.path.relpath(path).strip('..\\').replace('\\','/')
        with open(path, 'r', encoding="utf-8", errors='ignore') as myfile:
            content = myfile.read().splitlines()
        d['content'] = content