首页 > 解决方案 > 如何遍历多个文件夹并附加文件?

问题描述

我下载了我的 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 文件

标签: pythonjsondirectory

解决方案


像这样的东西会起作用吗?

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)

推荐阅读