python - 在每个文件合并后添加换行符
问题描述
我有很多 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": ""}
感谢任何帮助。
解决方案
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')