Python 循环写入json文件 解决内容覆盖+换行问题
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json

·
一般使用 open打开一个json文件为文件标识符,使用文件标识符来对文件进行写入:
import json
# save = dict() 为待保存的字典
with open("./res_video.json", 'w', encoding='utf-8') as fw:
json.dump(save, fw, indent=4, ensure_ascii=False)
json.dump会保存字典 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:
json.dump(save, fw, indent=4, ensure_ascii=False)
使用json.dump无法直接换行,例如:
{
"name": "51_20220401_17fe26c717a519265.mp4",
"url": "https://god-private.nos-jd.163yun.com/51_20220401_17fe26c717a519265.mp4?Signature=o8vcsZ9v9efgpJMKlAh89GRKk1OnZhQL6QuNVq4F%2BsE%3D&Expires=1649030436&NOSAccessKeyId=b62dbbae0edd4a80b38556a0780710db"
}{
"name": "50_20220401_17fe26cb2f9399922.mp4",
"url": "https://god-private.nos-jd.163yun.com/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:
json.dump(save, fw, indent=4, ensure_ascii=False)
fw.write('\n')
也可以使用费json.dumps 将dict() 转化为str 字符串后写入存储:
import json
# save = dict() 为待保存的字典
with open("./res_video.json", 'a', encoding='utf-8') as fw:
str = json.dumps(save,indent=4, ensure_ascii=False)
fw.write(str)
fw.write('\n')




适用于现代 C++ 的 JSON。
最近提交(Master分支:6 个月前 )
c67d5382
* :alembic: try matrix for latest
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :recycle: refactor from https://github.com/nlohmann/json/issues/4745#issuecomment-2810128420
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :construction_worker: simplify CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :construction_worker: simplify CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :rotating_light: fix cpplint warning
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :construction_worker: simplify CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
---------
Signed-off-by: Niels Lohmann <mail@nlohmann.me> 14 小时前
88c92e60
* :rotating_light: fix warnings
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :rotating_light: fix warnings
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :alembic: enable ranges support
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :fire: remove ci_nvhpc job
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :alembic: enable ranges support
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :fire: remove ci_nvhpc job
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* :rotating_light: fix warning
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
---------
Signed-off-by: Niels Lohmann <mail@nlohmann.me> 1 天前
更多推荐
所有评论(0)