gpt4 book ai didi

python-3.x - 附加到 pickle 文件而不删除

转载 作者:行者123 更新时间:2023-12-03 10:08:26 27 4
gpt4 key购买 nike

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

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

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

最佳答案

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com