如何向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 文件了。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步