Python 循环写入json文件 解决内容覆盖+换行问题

时间:2025-03-28 17:13:34

一般使用 open打开一个json文件为文件标识符,使用文件标识符来对文件进行写入:

import json
# save = dict() 为待保存的字典
with open("./res_video.json", 'w', encoding='utf-8') as fw:
    (save, fw, indent=4, ensure_ascii=False)

会保存字典 save的内容到文件,indent为保存格式,indent=2是保存为一行,indent=4会展开save字典中的没有键和键值

如果不行每次写入文件的内容被覆盖,with open()的打开格式需要为 a,以追加格式写入文件

import json
# save = dict() 为待保存的字典
with open("./res_video.json", 'a', encoding='utf-8') as fw:
    (save, fw, indent=4, ensure_ascii=False)

使用无法直接换行,例如:

{
  "name": "51_20220401_17fe26c717a519265.mp4",
  "url": "-jd./51_20220401_17fe26c717a519265.mp4?Signature=o8vcsZ9v9efgpJMKlAh89GRKk1OnZhQL6QuNVq4F%2BsE%3D&Expires=1649030436&NOSAccessKeyId=b62dbbae0edd4a80b38556a0780710db"
}{
  "name": "50_20220401_17fe26cb2f9399922.mp4",
  "url": "-jd./50_20220401_17fe26cb2f9399922.mp4?Signature=RsKoY89EaYhuWBho1hTwYS%2B%2FvHky1qcK84dzr5XKIXE%3D&Expires=1649030451&NOSAccessKeyId=b62dbbae0edd4a80b38556a0780710db"
}

需要使用write()格外输入换行符 \n

import json
# save = dict() 为待保存的字典
with open("./res_video.json", 'a', encoding='utf-8') as fw:
    (save, fw, indent=4, ensure_ascii=False)
    ('\n')

也可以使用费 将dict() 转化为str 字符串后写入存储:

import json
# save = dict() 为待保存的字典
with open("./res_video.json", 'a', encoding='utf-8') as fw:
    str = (save,indent=4, ensure_ascii=False)
    (str)
    ('\n')