[Tutor] Pickle Class Instances

Andreas Perstinger andreas.perstinger at gmx.net
Tue Nov 1 07:53:04 CET 2011

On 2011-11-01 06:31, Rinu Boney wrote:
> def add_book(b):
>      fo=open('books.dat','wb')
>      pickle.dump(b,fo)
>      fo.close()
> The Display After Unpickling Shows only the last Class Instance.
> How To Display All The Data In The File ?

You haven't shown us the complete program (how to you call "add_book" 
and "display_books"?) but I guess that you call "add_book" with one 
instance (if not, you can ignore the rest). In that case there is no 
more data in the file.

In your "add_book" function you open the file "books.at" and just save 
one instance. The next time you call the function with another instance 
you overwrite the former, because opening the same file with the 
parameter "w" (or in your case "wb") deletes any already existing content.

What you probably want is to put all the instances into a list and save 
this list. When you later read the file, you'll get the list back and 
you can iterate over it for displaying.

Bye, Andreas

More information about the Tutor mailing list