如何在json文件中放置空行

2024-10-03 09:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试做一个python的抓取脚本,它获取信息并将其放入json文件中

但问题是,我不知道在收到我的信息后如何去换行。 我的json文件是:

Test1:blablablablaTest2:Blablabal:Test3BLABLABLA etc...

我想要

Test1:blablabl
test2:blablabla
etc

这是我的代码: (我试图放置'\n',但它在行的末尾写入了\n)

with open(source, 'w', encoding='utf-8') as f:
   json.dump(date_json, f, ensure_ascii=False, indent=2)
   json.dump(numeroFacture_json, f, ensure_ascii=False, indent=2)
   json.dump(montantTotal_json, f, ensure_ascii=False, indent=2)
   json.dump(tva_json, f, ensure_ascii=False, indent=2)
   json.dump(montantHt_json, f, ensure_ascii=False, indent=2)

谢谢


Tags: 文件脚本信息jsonfalseasciietcdump
1条回答
网友
1楼 · 发布于 2024-10-03 09:11:35

要做到这一点,只需在每个json.dump句子后面添加f.write("\n"),如下所示:

with open(source, 'w', encoding='utf-8') as f:
    json.dump(date_json, f, ensure_ascii=False, indent=2)
    f.write("\n")
    json.dump(numeroFacture_json, f, ensure_ascii=False, indent=2)
    f.write("\n")
    json.dump(montantTotal_json, f, ensure_ascii=False, indent=2)
    f.write("\n")
    json.dump(tva_json, f, ensure_ascii=False, indent=2)
    f.write("\n")
    json.dump(montantHt_json, f, ensure_ascii=False, indent=2)

相关问题 更多 >