将python对象(字典)附加到现有的pickle文件

时间:2016-12-10 20:14:58

标签: python-3.x serialization pickle

我是python的新手,我正在尝试使用pickle将一些python对象存储到一个文件中。我知道在向现有pickle文件添加新对象时,我可以加载现有对象并连接新对象:

# l is a list of existing dictionaries stored in the file:
l = pickle.load(open('existing_file.p', 'rb'))
new_dict = {'a': 1, 'b':2}
l = l + [new_dict]
# overwriting old file with the new content
pickle.dump(open('existing_file.p', 'rw'), l)

我想检查是否有更好的方法将类似字典的对象附加到现有的pickle文件而不覆盖整个内容。 任何提示或建议将不胜感激。

1 个答案:

答案 0 :(得分:1)

pickle知道其序列化对象的长度,因此您可以继续将新的pickle对象附加到列表的末尾,并在以后一次读取它们。通过附加到我的pickle文件创建一些pickle对象后,

>>> with open('test.pickle', 'ab') as out:
...     pickle.dump((1,2,3), out)
... 
>>> with open('test.pickle', 'ab') as out:
...     pickle.dump((4,5,6), out)

我可以阅读它们,直到我得到EOFError才知道我已经完成了

>>> my_objects = []
>>> try:
...     with open('test.pickle', 'rb') as infile:
...         while True:
...             my_objects.append(pickle.load(infile))
... except EOFError:
...     pass
... 
>>> my_objects
[(1, 2, 3), (4, 5, 6)]