I've tried to write to a file using binary mode with the pickle module. This is an example:
import pickle
file = open("file.txt","wb")
dict = {"a":"b","c":"d"}
pickle.dump(dict, file)
file.close()
But this method deletes the other dicts written before. How can I write without deleting the other things in the file?
You need to append to the original file, but first unpickle the contents (I assume the original file had pickled content). What you were doing is simply overwriting the existing file with a new pickled object
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With