将目录树表示为JSON
有没有简单的方法来生成这样的JSON文件?我发现了os.walk()
和os.listdir()
这两个函数,可以用它们递归地进入文件夹,构建一个Python对象。不过,这听起来像是在重复造轮子,可能有人知道已经可以用的代码来完成这个任务?
{
"type": "directory",
"name": "hello",
"children": [
{
"type": "directory",
"name": "world",
"children": [
{
"type": "file",
"name": "one.txt"
},
{
"type": "file",
"name": "two.txt"
}
]
},
{
"type": "file",
"name": "README"
}
]
}
3 个回答
2
我刚刚需要做这个(差不多吧),所以找到了这个页面,但上面的内容并没有递归到子目录里。
所以这个版本只处理目录,不处理文件,不过你可以自己加上文件的处理。
首先生成一个嵌套的 Python 字典:
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
其次,使用 json
模块把它转换成 JSON 格式。
51
我觉得这个任务并不是“重复造轮子”。不过,你可以很轻松地用你提到的工具来完成这个任务:
import os
import json
def path_to_dict(path):
d = {'name': os.path.basename(path)}
if os.path.isdir(path):
d['type'] = "directory"
d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\
(path)]
else:
d['type'] = "file"
return d
print json.dumps(path_to_dict('.'))