繁体   English   中英

将字典转换为Json并追加到文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM