【问题标题】:Write a list of dictionaries row by row on a file在文件上逐行写入字典列表
【发布时间】:2018-08-18 09:33:05
【问题描述】:

我需要将字典逐行附加到文件中。 最后,我将在文件中有一个字典列表。

我的天真尝试是:

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

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

【问题讨论】:

  • 您可能应该改用fout.write(',')resu 是什么格式?你得到什么错误?当您逐行说字典列表时,行是什么意思?这个相关的SO post 也可能有帮助。
  • 您需要更具体一些,您的意思是字典列表中的每个字典都应该写入文件中的一行吗?输入和输出示例会有所帮助。
  • @thmsdnnr :这确实是我的错误。谢谢!

标签: python json file


【解决方案1】:

如果您需要按特定顺序保存多个字典,为什么不先将它们放在一个列表对象中,然后使用 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()

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多