我尝试使用带有 pickle 模块的二进制模式写入文件。这是一个例子:

    import pickle
    file = open("file.txt","wb")
    dict = {"a":"b","c":"d"}
    pickle.dump(dict, file)
    file.close()

但是这个方法会删除之前写的其他dicts。如何在不删除文件中的其他内容的情况下进行写入?

最佳答案

您需要附加到原始文件,但首先解压缩内容(我假设原始文件已包含内容)。
您所做的只是用新的 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)

关于python-3.x - 附加到pickle文件而不删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45505850/

10-16 05:19