May 10, 2013

Object serialization in Python using Pickle

Pickle is Python's object serialization mechanism. To pickle an object
import pickle

k = ... # an object, say an ndarray

pickle.dump(k, open("housing_prices_shuffled.p", "wb"))
This creates a file "housing_prices_shuffled.p" which holds a serialized representation of the object which was pickled. To unpickle
k = pickle.load(open("housing_prices_shuffled.p", "rb"))
cPickle
An faster alternative to pickle is cPickle. The pickling/unpickling steps with cPickle are the same as the above. To use cPickle, import cPickle as pickle. i.e.
import cPickle as pickle