Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字典转换为Json并附加到文件_Python_Json_File_Dictionary - Fatal编程技术网

Python 将字典转换为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)

场景是我需要将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)
            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
    参数没有意义。您必须传递字典,否则
    update
    方法将不起作用。如果对象是“falsy”,我们可以跳过更新
  • 不要使用
    dict
    作为变量名
  • 最后,用新版本的数据覆盖文件(
    w+
    r+
    应保留为固定大小/二进制文件,而不是文本/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)

else
中删除
f=open…
,完成后关闭文件处理程序:
f.close()
(在函数末尾)也不要使用w+模式。使用单独的读写块。请注意,打开一个已经打开的文件从来都不是一个好主意。