1. Home
  2. Computing & Technology
  3. Python

Using Pickle to Save Objects in Python

From , former About.com Guide

Pickle is an important module whenever you need persistence between user sessions. Whether your are programming for a database, game, forum, or some other application that must save information between sessions, you will find pickle helpful for saving identifiers and settings. As a module, pickle provides for the saving of Python objects between processes.

The concept of pickling is known variously as serialisation, marshalling, or flattening. The point is the same: Save an object to a file for later retrieval. Pickling accomplishes this simply by writing the object as one long stream of bytes. To write an object to a file, you would use code that fits the following syntax:

import pickle
object = Object()
filehandler = open(filename, 'w')
pickle.dump(object, filehandler)

A real-world example would look like this:

import pickle
import math
object_pi = math.pi
file_pi = open('filename_pi.obj', 'w')
pickle.dump(object_pi, file_pi)
This snippet writes the contents of object_pi to the file handler file_pi, which in turn is bound to the file 'filename_pi.obj' in the directory of execution.

To restore the value of the object to memory, load the object from the file. Assuming that pickle has not yet been imported for use, start by importing it:

import pickle
filehandler = open(filename, 'r')
object = pickle.load(filehandler)

Carrying on from our previous syntax, the following code would restore the value of pi:

import pickle
file_pi2 = open('filename_pi.obj', 'r')
object_pi2 = pickle.load(file_pi2)
The object is then ready for use once again, this time as 'object_pi2'. You can, of course, re-use the original names, if necessary. I have used distinct names here for exemplary reasons only.

Explore Python
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Python Library
  5. Python Objects and Persistance: Using Pickle to Save Objects in Python>

©2009 About.com, a part of The New York Times Company.

All rights reserved.