A Byte of Python

Pickle

Python provides a standard module called pickle using which you can store any Python object in a file and then get it back later intact. This is called storing the object persistently.

There is another module called cPickle which functions exactly same as the pickle module except that it is written in the C language and is (upto 1000 times) faster. You can use either of these modules, although we will be using the cPickle module here. Remember though, that we refer to both these modules as simply the pickle module.

Pickling and Unpickling

Example 12.2. Pickling and Unpickling

				
#!/usr/bin/python
# Filename: pickling.py

import cPickle as p
#import pickle as p

shoplistfile = 'shoplist.data' # the name of the file where we will store the object

shoplist = ['apple', 'mango', 'carrot']

# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()

del shoplist # remove the shoplist

# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
				
				

Output

				
$ python pickling.py
['apple', 'mango', 'carrot']
				
				

How It Works

First, notice that we use the import..as syntax. This is handy since we can use a shorter name for a module. In this case, it even allows us to switch to a different module (cPickle or pickle) by simply changing one line! In the rest of the program, we simply refer to this module as p.

To store an object in a file, first we open a file object in write mode and store the object into the open file by calling the dump function of the pickle module. This process is called pickling.

Next, we retrieve the object using the load function of the pickle module which returns the object. This process is called unpickling.