Python by Swaroop C H - HTML preview
Download the book in PDF, ePub, Kindle for a complete version.
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()
# 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 orpickle) by simply changing one line! In the rest of the program, we simply refer to this module asp.
To store an object in a file, first we open afile object in write mode and store the object into the open file by calling thedump function of the pickle module. This process is called pickling. Next, we retrieve the object using theload function of thepickle module which returns the object. This process is called unpickling.