O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Persistence

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required