python - Python - 将目录结构表示为 JSON 并读取每个文件的内容
问题描述
问题的第一部分有答案,我从这个答案中得到帮助来表示 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")))
推荐阅读
- pandas - 如何使用 pd.to_datetime() 先显示日期?
- html - 如何摆脱 Material DatetimePicker 时间下划线
- reactjs - Redux Toolkit 查询无效的 isLoading 状态
- javascript - JS 从 URL 参数中预填充输入字段
- javascript - 在 Vuejs 3 中实现插件系统
- php - 我们可以在 php 中执行时检查内存使用情况,如果内存达到 80% 或更多或在浏览器崩溃之前使作业失败
- loops - 如何在伪代码中声明维数组?
- ios - CollectionView - 停止/防止部分标题滚动超出某个点
- python - Pytest 的“caplog”夹具的类型提示是什么?
- regex - 如何删除前导字符直到满足 1-9