Pickle vs XML for file I/O

crystalattice crystalattice at gmail.com
Wed Aug 2 13:21:04 EDT 2006


Marc 'BlackJack' Rintsch wrote:
> In <1154451307.232785.282080 at m79g2000cwm.googlegroups.com>, crystalattice
> wrote:
>
> >> What are the problems you fear when using `shelve` by the way?
> >>
> > The ideas I got about shelve are mostly due to this thread:
> > http://tinyurl.com/lueok.  There weren't any other threads
> > contradicting the information so I figured it has merit.
>
> Main complaint seemed to be that data might be corrupted when the program
> terminates "abnormal" while writing the data.  You have the very same
> problem with pickle or XML serialization.  If the program gets interrupted
> after only half the data is written to disk you lose information.
>
> > Actually, not many people seem to use shelve very much; pickle is used
> > more often so I decided to give it a try and see how it works for me.
>
> They have a slightly different use case.  `pickle` stores single objects
> and `shelve` is a sort of persistent dictionary that maps strings to
> objects.  So if you want to save a party of characters and load them back
> together than pickle a list with those characters.  If you want a database
> of many characters the player can choose from than you might want to store
> them in a `shelve`.
>
> Ciao,
> 	Marc 'BlackJack' Rintsch

Okay, that makes sense.  I was able to figure out how to pickle
yesterday.  It's not as hard as I thought (obviously); my confusion
originally came from thinking I needed to pickle each item of the class
separately but I realized that pickling a class instance worked too.

One other question though (hope it doesn't sound silly/stupid).  Your
suggestion to "pickle a party" using a list has me thinking:  can a
list store class instances?  I imagine it can though I don't know if
there may be bad juju if I tried, like data corruption or errors or
something.  I've only been using classes for a few weeks so I don't
know very much about them.

For example, if I wanted to store a party of characters, rather than
pickling each person separately could I put each character instance in
a list then pickle the list?  Like this:

char1 = Character()
char2 = Character()
char3 = Character()
party = [char1, char2, char3]
file = open("partyfile.dat", "w")
pickle.dump(party, file)




More information about the Python-list mailing list