我試着用pickle模塊寫入使用二進制模式的文件。這是一個例子:附加到pickle文件而不刪除
import pickle
file = open("file.txt","wb")
dict = {"a":"b","c":"d"}
pickle.dump(dict, file)
file.close()
但是這種方法刪除了之前寫的其他字典。如何在不刪除文件中的其他內容的情況下編寫代碼?
我試着用pickle模塊寫入使用二進制模式的文件。這是一個例子:附加到pickle文件而不刪除
import pickle
file = open("file.txt","wb")
dict = {"a":"b","c":"d"}
pickle.dump(dict, file)
file.close()
但是這種方法刪除了之前寫的其他字典。如何在不刪除文件中的其他內容的情況下編寫代碼?
你需要附加到原始文件,但首先取消內容(我假設原始文件已酸洗內容)。 什麼你做的是簡單地覆蓋了新醃製的對象
import pickle
#create the initial file for test purposes only
obj = {"a":"b","c":"d"}
with open("file.txt","wb") as f:
pickle.dump(obj, f)
#reopen and unpickle the pickled content and read to obj
with open("file.txt","rb") as f:
obj = pickle.load(f)
print(obj)
#add to the dictionary object
obj["newa"]="newb"
obj["newc"]="newd"
with open("file.txt","wb") as f:
pickle.dump(obj, f)
#reopen and unpickle the pickled content and read to obj
with open("file.txt","rb") as f:
obj = pickle.load(f)
print(obj)
謝謝,我會嘗試在我的代碼上應用這個 – taynan
您可以在一個文件中串聯醃製對象的現有文件,所以沒有必要讀取該文件,並改寫它。你只需要附加到文件,而不是覆蓋它。
替換:
file = open("file.txt","wb")
有了:
file = open("file.txt","ab")
有關可用的文件模式和他們所做的事情,看到documentation的更多信息。
請記住,您需要多個pickle.load()
才能取消數據。
相關:https://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file。請注意,如果它能和pickle文件一起工作的話。 – Evert