python - 将字典转换为 Json 并附加到文件
问题描述
场景是我需要将字典对象转换为 json 并写入文件。每次 write_to_file() 方法调用都会发送新的 Dictionary 对象,我必须将 Json 附加到文件中。以下是代码
def write_to_file(self, dict=None):
f = open("/Users/xyz/Desktop/file.json", "w+")
if json.load(f)!= None:
data = json.load(f)
data.update(dict)
f = open("/Users/xyz/Desktop/file.json", "w+")
f.write(json.dumps(data))
else:
f = open("/Users/xyz/Desktop/file.json", "w+")
f.write(json.dumps(dict)
收到此错误“无法解码 JSON 对象”并且未将 Json 写入文件。任何人都可以帮忙吗?
解决方案
这看起来过于复杂且非常错误。在模式下多次打开文件w+
并读取两次不会让您无处可去,但会创建一个json
无法读取的空文件。
- 我会测试文件是否存在,如果是,我正在阅读它(否则创建一个空字典)。
- 这个默认
None
参数没有意义。您必须传递字典,否则该update
方法将不起作用。好吧,如果对象是“假的”,我们可以跳过更新。 - 不要
dict
用作变量名 - 最后,用新版本的数据覆盖文件(
w+
并且r+
应该保留给固定大小/二进制文件,而不是 text/json/xml 文件)
像这样:
def write_to_file(self, new_data=None):
# define filename to avoid copy/paste
filename = "/Users/xyz/Desktop/file.json"
data = {} # in case the file doesn't exist yet
if os.path.exists(filename):
with open(filename) as f:
data = json.load(f)
# update data with new_data if non-None/empty
if new_data:
data.update(new_data)
# write the updated dictionary, create file if
# didn't exist
with open(filename,"w") as f:
json.dump(data,f)
推荐阅读
- javascript - TypeError: t 不是函数 - React
- mysql - MySQL 无法启动服务器
- python - 我如何使用泛型 API 视图获取带有 url 的图像位置以响应 django rest 框架
- android - 如何单击底部栏上的图标
- html - element.style 的连字符属性键的使用
- python - 有没有办法根据网格内的点密度为 3D 数据集着色?
- python - BeautifulSoup 无法找到解析的元素
- php - Laravel 8 belongsTo 关系不返回用户模型上的数据
- react-hooks - 下拉菜单不会随状态而变化
- highcharts - 如何在包装好的 Highcharts 气泡上显示系列名称?