如何向json 文件中追加内容

本文也算是一个小积累。

前提:使用python 写入json并追加内容。

错误实现:

with open(os.path.join(annotations_path, 'data.json'), 'a') as f:
    pass

这样会相当于写入多个字典。可以写入,但无法使用如下代码读取

with open(json_path) as f:
    annot = json.load(f)

正确方式:

# 先读取原始的json 文件
with open(os.path.join(annotations_path, 'data.json'), 'r') as f:
    content = json.load(f)
# 更新json,xx_dict为添加的新的内容
content.update(xx_dict)
# 写入到原来的文件中
with open(os.path.join(annotations_path, 'data.json'), 'w') as f_new:
    json.dump(content, f_new)

注意:如果data.json一开始什么都没有,需要向里面手动写入一个{}

这样就可以愉快的使用上面的代码读取 json 文件了。

参考链接

python:向json里面追加数据

posted @ 2022-08-11 10:29  cold_moon  阅读(1787)  评论(0编辑  收藏  举报