1

我正在尝试将大量列表存储在 json 文件中。这些列表是从一个长时间运行的过程中生成的,所以我想将新生成的信息添加到我的 json 文件中,因为它变得可用。

目前,为了扩展数据结构,我将 json 作为 Python 列表读入内存,将新数据附加到该列表中,然后用新创建的列表覆盖 json 文件中的旧数据。

def update_json_file(new_data):
    with open('mycoolfile.json', 'rb') as f: 
        jsondata = json.load(f)

    jsondata.append(new_data)
    with open('mycoolfile.json', 'wb') as f: 
        json.dump(jsondata, f)

有没有比将所有内容读入内存更好的方法?当然,随着文件大小的增加,这将不再是一个可行的策略。有没有一种简单的方法来扩展 json 文件中的结构?

4

1 回答 1

1

是的,正如 zaquest 所说,您可以搜索到文件的几乎末尾并覆盖外部列表的最终“]”。这里有一些东西可以说明如何做到这一点:

import json
import os

def append_list(json_filename, new_data):
    with open(json_filename, 'r+b') as f:
        f.seek(-1, os.SEEK_END)
        new_json = json.dumps(new_data)
        f.write(', ' + new_json + ']')

# create a test file
lists = [
    'This is the first list'.split(),
    "and here's another.".split(),
    [10, 2, 4],
]

with open('mycoolfile.json', 'wb') as f:
    json.dump(lists, f)

append_list('mycoolfile.json', 'New data.'.split())

with open('mycoolfile.json', 'rb') as f:
    jsondata = json.load(f)
    print json.dumps(jsondata, indent=4)

输出:

[
    [
        "This",
        "is",
        "the",
        "first",
        "list"
    ],
    [
        "and",
        "here's",
        "another."
    ],
    [
        10,
        2,
        4
    ],
    [
        "New",
        "data."
    ]
]
于 2013-10-05T03:03:01.627 回答