问题的第一部分有答案,我从 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
条件下会发生什么吗?或者也许还有其他方法?
最佳答案
事实证明,获取内容非常简单。作为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")))
关于Python - 将目录结构表示为 JSON 并读取每个文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54933319/