3

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?

glibdud
  • 7,550
  • 4
  • 27
  • 37
taynan
  • 67
  • 1
  • 7
  • Related: https://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file . Note sure if that'll work with a pickle file though. –  Aug 04 '17 at 11:42

2 Answers2

2

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)
Simon Black
  • 913
  • 8
  • 20
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.

glibdud
  • 7,550
  • 4
  • 27
  • 37