python - 如何遍历多个文件夹并附加文件?
问题描述
我下载了我的 Facebook Messenger 数据,它包含在一系列文件夹中,每个文件夹中都有一个 JSON 文件。我想编写一个脚本来遍历每个文件夹并将所有 JSON 附加在一起。
示例:在 '/home/Desktop/messages/inbox' 中有 10 个文件夹,名为['a','b','c','d','e','f','g','h','i','j']
.
每个文件夹中有一个 JSON 文件
[message_a.json, message_b.json, message_c.json, message_d.json, message_e.json, message_f.json, message_g.json. message_h.json, message_i.json, message_j.json]
谢谢!
以及每个文件夹中的 JSON 文件
解决方案
像这样的东西会起作用吗?
import json
import glob
directory = '/home/Desktop/messages/inbox'
outfile = '/home/Desktop/messages/inbox/merged_json.json'
result = []
for folder in os.listdir(directory):
for f in glob.glob(directory + "/" + folder + "*/.json"):
with open(f, "rb") as infile:
result.append(json.load(infile))
with open(outfile, "wb") as out:
json.dump(result, out)
推荐阅读
- arrays - 如何使用循环在 Assembly 中查找数组的最小值和最大值?
- java - GeoAPIContext 崩溃
- angular - Angular 6:TypeError:无法读取 null 的属性“scrollIntoView”
- angularjs - 如何为使用 ng-material-multilevel-menu 显示的数据附加椭圆
- java - 在场景生成器中处理鼠标事件时,Java FXML GridPane.getRowIndex(source) 总是返回 null
- java - 使用 react native 构建完整的应用程序后如何获取 java 代码?
- visual-studio - 将空白页添加到新的 C++/WinRT 桌面项目时出现无效标记错误
- java - 如何根据 2 个参数查询 SQLite 表?
- java - 在 Java 中安全地开发 SQL 查询
- reactjs - 用 Hooks 反应搜索栏