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

attaching python objects (dictionaries) to existing pickle file

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

# 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 知道其序列化对象的长度,因此您可以继续将新的 pickled 对象附加到列表的末尾,并在以后一次读取一个。通过附加到我的 pickle 文件创建一些 pickled 对象后,

>>> 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)]