【问题标题】:Add break line after each file merge在每个文件合并后添加换行符
【发布时间】:2019-03-17 21:40:50
【问题描述】:

我有很多 JSON 文件,如下所示:

例如

1.json

{"name": "one", "description": "testDescription...", "comment": ""}

test.json

{"name": "test", "description": "testDescription...", "comment": ""}

two.json

{"name": "two", "description": "testDescription...", "comment": ""}

...

我想将它们全部合并到一个 JSON 文件中,例如:

merge_json.json

{"name": "one", "description": "testDescription...", "comment": ""},
{"name": "test", "description": "testDescription...", "comment": ""},
{"name": "two", "description": "testDescription...", "comment": ""}

我有以下代码:

import json
import glob

result = []
for f in glob.glob("*.json"):
    with open(f, "r") as infile:
        try:
            result.append(json.load(infile))
        except ValueError as e:
            print(f,e)
result = '\n'.join(result)

with open("merged.json", "w", encoding="utf8") as outfile:
    json.dump(result, outfile)

我可以合并所有文件,但是所有文件都在一行中,添加每个文件后如何添加换行符:

代替:

{"name": "one", "description": "testDescription...", "comment": ""},{"name": "test", "description": "testDescription...", "comment": ""},{"name": "two", "description": "testDescription...", "comment": ""}

让他们喜欢:

merge_json.json

{"name": "one", "description": "testDescription...", "comment": ""},
{"name": "test", "description": "testDescription...", "comment": ""},
{"name": "two", "description": "testDescription...", "comment": ""}

感谢任何帮助。

【问题讨论】:

标签: python


【解决方案1】:
result = []
for f in glob.glob("*.json"):
    with open(f, "r") as infile:
        try:
            result.append(json.load(infile))
        except ValueError as e:
            print(f,e)

with open("merged.json", "a", encoding="utf8") as outfile:
    for i in result:
        json.dump(i, outfile)
        outfile.write('\n')

【讨论】:

    猜你喜欢
    • 2011-02-27
    • 2019-10-09
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    相关资源
    最近更新 更多