场景是我需要将字典对象转换为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没有写入文件。有人可以帮忙吗?
答案 0 :(得分:2)
这看起来过于复杂且非常错误。在w+
模式下多次打开文件并阅读两次将无法让您无处可寻,但会创建json
无法读取的空文件。
None
参数毫无意义。您必须传递字典,否则update
方法将无效。好吧,如果对象是“falsy”,我们可以跳过更新。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)