2016-12-10 129 views
1

我是python的新手,我試圖用pickle將幾個python對象存儲到文件中。我知道,同時增加新的對象,以現有的泡菜文件我可以加載現有的對象並連接新一:將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) 

我想檢查是否有附加的物體,像字典到什麼更好的辦法現有的酸洗文件而不覆蓋整個內容。 任何暗示或建議將不勝感激。

回答

1

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

非常感謝。它非常完美! –