代码之家  ›  专栏  ›  技术社区  ›  Mauro Gentile

在文件上逐行写入词典列表

  •  -1
  • Mauro Gentile  · 技术社区  · 7 年前

    我需要将字典逐行附加到文件中。 最后,我会在文件中列出一系列词典。

    我天真的尝试是:

    with open('outputfile', 'a') as fout:
        json.dump(resu, fout)
        file.write(',')
    

    但它不起作用。有什么建议吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Nathan Stanton    7 年前

    如果需要按特定顺序保存大量词典,为什么不先将它们放在列表对象中,然后使用json为您序列化整个过程?

    import json
    
    
    def example():
        # create a list of dictionaries
        list_of_dictionaries = [
            {'a': 0, 'b': 1, 'c': 2},
            {'d': 3, 'e': 4, 'f': 5},
            {'g': 6, 'h': 7, 'i': 8}
        ]
    
        # Save json info to file
        path = '.\\json_data.txt'
        save_file = open(path, "wb")
        json.dump(obj=list_of_dictionaries,
                  fp=save_file)
        save_file.close()
    
        # Load json from file
        load_file = open(path, "rb")
        result = json.load(fp=load_file)
        load_file.close()
    
        # show that it worked
        print(result)
        return
    
    
    if __name__ == '__main__':
        example()
    

    如果您的应用程序必须不时附加新词典,则可能需要执行更接近以下内容的操作:

    import json
    
    
    def example_2():
        # create a list of dictionaries
        list_of_dictionaries = [
            {'a': 0, 'b': 1, 'c': 2},
            {'d': 3, 'e': 4, 'f': 5},
            {'g': 6, 'h': 7, 'i': 8}
        ]
    
        # Save json info to file
        path = '.\\json_data.txt'
    
        save_file = open(path, "w")
        save_file.write(u'[')
        save_file.close()
    
        first = True
        for entry in list_of_dictionaries:
            save_file = open(path, "a")
            json_data = json.dumps(obj=entry)
            prefix = u'' if first else u', '
            save_file.write(prefix + json_data)
            save_file.close()
            first = False
    
        save_file = open(path, "a")
        save_file.write(u']')
        save_file.close()
    
        # Load json from file
        load_file = open(path, "rb")
        result = json.load(fp=load_file)
        load_file.close()
    
        # show that it worked
        print(result)
        return
    
    
    if __name__ == '__main__':
        example_2()