将Python词典列表追加到文件而不加载 [英] Append list of Python dictionaries to a file without loading it

查看:80
本文介绍了将Python词典列表追加到文件而不加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要一个包含字典列表的数据库文件:

Suppose I need to have a database file consisting of a list of dictionaries:

文件:

[
  {"name":"Joe","data":[1,2,3,4,5]},
  {   ...                         },
           ...
]

我需要一个函数来接收字典列表,如上所示,并将其附加到文件中.有什么方法可以实现此目标,例如使用json(或任何其他方法)而不加载文件?

I need to have a function that receives a list of dictionaries as shown above and appends it to the file. Is there any way to achieve that, say using json (or any other method), without loading the file?

注意:我需要的是将新词典添加到光盘上已经存在的文件中.

Note: What I need, is to append new dictionaries to an already existing file on the disc.

推荐答案

您可以使用json转储字典,每行一个.现在,每一行都是您编写的单个json字典.您可以松开外部列表,但是可以在现有文件中添加带有简单追加的记录.

You can use json to dump the dicts, one per line. Now each line is a single json dict that you've written. You loose the outer list, but you can add records with a simple append to the existing file.

import json
import os

def append_record(record):
    with open('my_file', 'a') as f:
        json.dump(record, f)
        f.write(os.linesep)

# demonstrate a program writing multiple records
for i in range(10):
    my_dict = {'number':i}
    append_record(my_dict)

列表可以在以后组装

with open('my_file') as f:
    my_list = [json.loads(line) for line in f]

文件看起来像

{"number": 0}
{"number": 1}
{"number": 2}
{"number": 3}
{"number": 4}
{"number": 5}
{"number": 6}
{"number": 7}
{"number": 8}
{"number": 9}

这篇关于将Python词典列表追加到文件而不加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆