将Python词典列表附加到文件而不加载它

jaz*_*lue 8 python json pickle

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

文件:

[
  {"name":"Joe","data":[1,2,3,4,5]},
  {   ...                         },
           ...
]
Run Code Online (Sandbox Code Playgroud)

我需要一个函数来接收如上所示的字典列表并将其附加到文件中.有没有办法实现这一点,比如使用json(或任何其他方法),而不加载文件?

EDIT1:注意:我需要的是将新词典附加到光盘上已有的文件中.

tde*_*ney 21

您可以使用json转储序列,每行一个.现在每行都是你写过的单个json词典.您松开了外部列表,但您可以添加带有简单附加到现有文件的记录.

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)
Run Code Online (Sandbox Code Playgroud)

该列表可以稍后组装

with open('my_file') as f:
    my_list = [json.loads(line) for line in f]
Run Code Online (Sandbox Code Playgroud)

该文件看起来像

{"number": 0}
{"number": 1}
{"number": 2}
{"number": 3}
{"number": 4}
{"number": 5}
{"number": 6}
{"number": 7}
{"number": 8}
{"number": 9}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果需要保持文件为有效json,则可以执行以下操作:

import json

with open (filepath, mode="r+") as file:
    file.seek(0,2)
    position = file.tell() -1
    file.seek(position)
    file.write( ",{}]".format(json.dumps(dictionary)) )
Run Code Online (Sandbox Code Playgroud)

这将打开文件以供读取和写入。然后,它到达文件的末尾(末尾为零字节)以找出文件末尾的位置(相对于文件的开头),并返回最后一个字节,这在json文件中应表示字符]。最后,它将新字典添加到结构中,覆盖文件的最后一个字符并使其保持有效的json。它不会将文件读入内存。已在Python 3.4.3中对ANSI和utf-8编码文件(带有小型和大型(5 GB)伪文件)进行了测试。

一个变体,如果您还os导入了模块:

import os, json

with open (filepath, mode="r+") as file:
    file.seek(os.stat(filepath).st_size -1)
    file.write( ",{}]".format(json.dumps(dictionary)) )
Run Code Online (Sandbox Code Playgroud)

它定义了文件的字节长度,以减少少一个字节的位置(如上例所示)。