问题的第一部分有答案,我从this答案中获得了帮助,以表示JSON中的目录结构。但是,我还需要阅读每个存在的文件的内容。
当前我的代码是:
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"
#contents = Something to read the contents??
#d['contents'] = contents
return d
print (json.dumps(path_to_dict("F:\\myfolder")))
当前输出为:
{"name": "myfolder", "type": "directory", "children": [{"name": "data", "type": "directory", "children": [{"name": "xyz.txt", "type": "file"}]}, {"name": "text", "type": "directory", "children": [{"name": "abc.txt", "type": "file"}]}]}
因此,基本上,每当遇到文件时,我都需要另一个标签contents
。
有人可以帮忙弄清楚在else
条件下会发生什么吗?也许还有其他方法?
答案 0 :(得分:0)
事实证明,获取内容非常简单。作为Python的新手,我一开始无法理解它。这是我解决的方法。
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"
with open('data.txt', 'r') as myfile:
contents=myfile.read().replace('\n', '')
d['contents'] = contents
return d
print (json.dumps(path_to_dict("F:\\myfolder")))