Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book