Linux/Unix > Python Essential Reference, Second Edition > 9. Input and Output > Persistence | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105085094125061049248110

### 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
    object = someObject()
    dbase = shelve.open(filename)    # Open a database
    dbase['key'] = object            # Save object in database
    ...
    object = dbase['key']            # Retrieve it
    dbase.close()                    # Close the database

In both cases, only serializable objects can be saved to a file. Most Python objects can be serialized, but special-purpose objects such as files maintain an internal state that cannot be saved and restored in this manner. For more details about the `pickle` and `shelve` modules, see Appendix A, “The Python Library.”

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.