首页 > 解决方案 > 将字典转换为 Json 并附加到文件

问题描述

场景是我需要将字典对象转换为 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 写入文件。任何人都可以帮忙吗?

标签: pythonjsonfiledictionary

解决方案


这看起来过于复杂且非常错误。在模式下多次打开文件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)

推荐阅读