[Tutor] Re: newbie intro to pickle

Andrei project5 at redrival.net
Sat Apr 16 11:16:32 CEST 2005

D. Hartley <denise.hartley <at> gmail.com> writes:

> So the .dump command is, in effect, saving the file, correct? which
> takes the object you're saving (in my case it would be
> high_scorelist), and ("filename","..... what is the "w" ?)  Why does
> the temp file you're saving into end in .pik?

Pickling simply converts an object to a string (unpickling does the opposite,
convert a string to an object). The dump() function writes the generated string
directly to a file, but you can use the dumps() function to get the generated
string as such and do something else with it (e.g. put it in a database, send it
by mail, whatever).

>>> mylist = [1, 2, 34, 4.2, 'abc']
>>> s = pickle.dumps(mylist)
>>> s # display the string
>>> pickle.loads(s)
[1, 2, 34, 4.2000000000000002, 'abc']

Pickling is also very useful when combined with the bsddb module, because you
get a fast database which functions very much like a dictionary, and in which
you can put anything you like, as long as you pickle it first.

>>> import bsddb
>>> mydb = bsddb.btopen('game.db')
>>> mydb['highscores'] = pickle.dumps(mylist)
>>> mydb['highestlevel'] = pickle.dumps(21)
>>> mydb['lastplayer'] = pickle.dumps('John Doe')
>>> mydb.close()
>>> mydb = bsddb.btopen('game.db')
>>> pickle.loads(mydb['lastplayer'])
'John Doe'

This is not useful for small amounts of data like the highscores list, but if
you have more data (e.g. level data, dialog texts) and you need quick access to
it without having to keep everything in memory all the time, bsddb is a
comfortable option.



More information about the Tutor mailing list