我试着用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