【问题标题】:Building JSON object from recursive directory tree traversal从递归目录树遍历构建 JSON 对象
【发布时间】:2021-11-09 05:01:20
【问题描述】:

我正在遍历包含目录和文件的目录树。我知道我可以为此使用 os.walk,但这只是我正在做的一个示例,最终结果必须是递归的。

获取数据的函数如下:

def walkfn(dirname):
    for name in os.listdir(dirname):
        path = os.path.join(dirname, name)
        if os.path.isdir(path):
            print(name)
            walkfn(path)
        elif os.path.isfile(path):
            print(name)

假设我们有一个这样的目录结构:

testDir/
    a/
        1/
        2/
            testa2.txt
        testa.txt
    b/
        3/
            testb3.txt
        4/

上面的代码将返回以下内容:

a
testa.txt
1
2
testa2.txt
c
d
b
4
3
testb3.txt

目前它正在做我所期望的,并且值都是正确的,但我正在尝试将这些数据放入 JSON 对象中。我已经看到我可以将它们添加到嵌套字典中,然后将其转换为 JSON,但是我在使用这种递归方法将它们放入嵌套字典时失败了。

我期待的 JSON 会是这样的:

{
    "test": {
        "b": {
            "4": {},
            "3": {
                "testb3.txt": null
            }
        },
        "a": {
            "testa.txt": null,
            "1": {},
            "2": {
                "testa2.txt": null
            }
        }
    }
}

【问题讨论】:

    标签: json python-3.x dictionary recursion


    【解决方案1】:

    您应该在递归函数中传递 json_data:

    import os
    from pprint import pprint
    from typing import Dict
    
    
    def walkfn(dirname: str, json_data: Dict=None):
        if not json_data:
            json_data = dict()
        for name in os.listdir(dirname):
            path = os.path.join(dirname, name)
            if os.path.isdir(path):
                json_data[name] = dict()
                json_data[name] = walkfn(path, json_data=json_data[name])
            elif os.path.isfile(path):
                json_data.update({name: None})
        return json_data
    
    
    json_data = walkfn(dirname="your_dir_name")
    pprint(json_data)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-14
      • 2018-07-12
      • 2014-03-11
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      相关资源
      最近更新 更多