在文件上逐行写出字典列表

时间:2018-03-09 18:32:54

标签: python json file

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

我天真的尝试是:

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

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

1 个答案:

答案 0 :(得分: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()