[英]Converting dictionary as Json and append to a file
场景是我需要将字典对象转换为json并写入文件。 新的Dictionary对象将在每次write_to_file()方法调用时发送,并且我必须将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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.