Python 将字典转换为Json并附加到文件
场景是我需要将dictionary对象转换为json并写入文件。每次write_to_file()方法调用时都会发送新的Dictionary对象,我必须将Json附加到文件中Python 将字典转换为Json并附加到文件,python,json,file,dictionary,Python,Json,File,Dictionary,场景是我需要将dictionary对象转换为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)
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
无法读取的空文件
- 我将测试文件是否存在,如果存在,我正在读取它(否则创建一个空的dict)
- 这个默认的
参数没有意义。您必须传递字典,否则None
方法将不起作用。如果对象是“falsy”,我们可以跳过更新update
- 不要使用
作为变量名dict
- 最后,用新版本的数据覆盖文件(
和w+
应保留为固定大小/二进制文件,而不是文本/json/xml文件)r+
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)
从
else
中删除f=open…
,完成后关闭文件处理程序:f.close()
(在函数末尾)也不要使用w+模式。使用单独的读写块。请注意,打开一个已经打开的文件从来都不是一个好主意。