2013-10-05 72 views
1

我试图在json文件中存储列表的大列表。这些列表是从长时间运行的进程生成的,所以我想在新的信息添加到我的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文件内部的结构?

+0

你不能将数据插入文件的中间,期。如果你想有效地做到这一点,请使用某种数据库。 – millimoose

+0

我同意上面的数据库评论。 sqlite非常易于使用python。当需要json文件时,可以根据需要构建它。 –

+0

@JoshSmeaton好吧。谢谢你的提示。看来我该终于学习数据库的工作方式了!我会检查出sqlite –

回答

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." 
    ] 
] 
相关问题