我尝试使用pickle模块使用二进制模式写入文件。这是一个例子:
import pickle
file = open("file.txt","wb")
dict = {"a":"b","c":"d"}
pickle.dump(dict, file)
file.close()
但是这种方法删除了之前写的其他词。如何在不删除文件中的其他内容的情况下编写?
答案 0 :(得分:1)
You can concatenate pickled objects in a file, so it's not necessary to read the file in and rewrite it. You simply need to append to the file, rather than overwriting it.
Replace:
file = open("file.txt","wb")
With:
file = open("file.txt","ab")
For more information on the file modes available and what they do, see the documentation.
And remember that you'll need multiple pickle.load()
s to unpickle the data.
答案 1 :(得分:0)
您需要附加到原始文件,但首先取消内容(我假设原始文件有腌制内容)。 你正在做的只是用一个新的pickle对象覆盖现有文件
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)