Represent directory tree as JSON

后端 未结 3 989
甜味超标
甜味超标 2020-12-13 07:17

Is there any easy way to generate such a JSON? I found os.walk() and os.listdir(), so I may do recursive descending into directories and build a py

3条回答
  •  有刺的猬
    2020-12-13 07:38

    I just had to do this (well, almost) so hit this page but the above doesn't recurse into subdirectories.

    So this version only handles directories, not files, but you could add those.

    First generate a nested python dict:

    def fs_tree(root):
        results = {}
        for (dirpath, dirnames, filenames) in os.walk(root):
            parts = dirpath.split(os.sep)
            curr = results
            for p in parts:
                curr = curr.setdefault(p, {})
        return results
    

    Secondly dump that to json using the json module.

提交回复
热议问题