每个文件合并后添加换行 - 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')

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

如何在python中将从PDF提取的文本格式化为json - python

我已经使用pyPDF2提取了一些文本格式的发票PDF。我想将此文本文件转换为仅包含重要关键字和令牌的json文件。输出应该是这样的:#PurchaseOrder {"doctype":"PO", "orderingcompany":"Demo Company", "su…