Python provides a standard module called pickle which you can use to store any Python object to a file and then get it back later. This is called storing the object persistently.
There is another module called cPickle which acts just the pickle module except that 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 here we refer to both these modules as the pickle module.
Example 12.2. Pickling and Unpickling
#!/usr/bin/python # Filename: pickling.py import cPickle shoplistfile = 'shoplist.data' # The name of the file we will use shoplist = ['apple', 'mango', 'carrot'] # Write to the storage f = file(shoplistfile, 'w') cPickle.dump(shoplist, f) # dump the data to the file f.close() del shoplist # Remove shoplist # Read back from storage f = file(shoplistfile) storedlist = cPickle.load(f) print storedlist
We create a file object in write mode and then store the object into the opened file by calling the dump function of the pickle module which stores the object into the file. 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.