2

I have pickled objects to a file in append mode but it only reads a single object. Here's the code. I don't know what I am doing wrong.

with open('notes.pkl', 'ab') as fileObject:                #append
    pickle.dump(obj, fileObject, pickle.HIGHEST_PROTOCOL)

with open('notes.pkl', 'rb') as input:                     #read
    obj= pickle.load(input)
    //perform tasks for each obj unpickled from the file
Me95
  • 45
  • 1
  • 4
  • Woah, I must be hallucinating today because I didn't see your code when I first opened this. Have you tried writing the pickle file as `wb` instead of appending? Also, what are you pickling? – RattleyCooper Apr 08 '16 at 16:42
  • you need to call "pickle.load" repeatedly until you hit end-of-file. – muratgu Apr 08 '16 at 16:47
  • I'm pickling a simple class with three data members. If I use wb it overwrites the previous object, and I need to maintain a series of objects – Me95 Apr 08 '16 at 16:57
  • thanks @muratgu! Works like a charm. – Me95 Apr 08 '16 at 17:03

1 Answers1

-1

You need to call pickle.load repeatedly until you hit end-of-file.

muratgu
  • 7,241
  • 3
  • 24
  • 26