Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to a pickle file without deleting

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?

like image 538
taynan Avatar asked Sep 17 '25 08:09

taynan


1 Answers

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)
like image 185
Simon Black Avatar answered Sep 19 '25 09:09

Simon Black