[英]Converting dictionary as Json and append to a file
Scenario is i need to convert dictionary object as json and write to a file . 场景是我需要将字典对象转换为json并写入文件。 New Dictionary objects would be sent on every write_to_file() method call and i have to append Json to the file .Following is the code
新的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)
Getting this error "No JSON object could be decoded" and Json is not written to the file. 收到此错误“无法解码JSON对象”,并且Json未写入文件。 Can anyone help ?
有人可以帮忙吗?
this looks overcomplex and highly buggy. 这看起来过于复杂且高度错误。 Opening the file several times, in
w+
mode, and reading it twice won't get you nowhere but will create an empty file that json
won't be able to read. 在
w+
模式下多次打开文件,并读取两次不会无所适从,但会创建一个json
无法读取的空文件。
None
argument makes no sense. None
参数毫无意义。 You have to pass a dictionary or the update
method won't work. update
方法将无效。 Well, we can skip the update if the object is "falsy". dict
as a variable name dict
作为变量名 w+
and r+
should be reserved to fixed size/binary files, not text/json/xml files) w+
和r+
应该保留为固定大小/二进制文件,而不是text / json / xml文件) Like this: 像这样:
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.