It’s often necessary to save and restore the contents of an object to a file. One approach to this problem is to write a pair of functions that read and write data from a file in a special format. An alternative approach is to use the pickle and shelve modules.
The pickle module serializes an object into a stream of bytes that can be written to a file. For example, the following code writes an object to a file:
import pickle object = someObject() f = open(filename,'w') pickle.dump(object, f) # Save object
To restore the object, you can use the following code:
import pickle f = open(filename,'r') object = pickle.load(f) # Restore the object
The shelve module is similar, but saves objects in a dictionary-like database:
import shelve ...