Python – Really Simple cPickle

The cPickle module lets you quickly save an object in your Python program to disk for later use. It’s pretty useful if you want your program to save some information but don’t feel like figuring out a file format, and then implementing it.

In the programming world, they call this concept “object serialization”.

Below is a code snippet that I use when I want to pickle something. See the official documention for more examples and sophisticated uses.

import cPickle
SAVE_PATH=r'C:\\my_object.p'

def save(your_object):
    # Pickle the list using the highest protocol available.
    cPickle.dump(your_object, file(SAVE_PATH, 'wb'), -1)

def load():
    if os.path.exists(SAVE_PATH):
        return cPickle.load(file(SAVE_PATH,'rb'))
    else:
        return None

NOTE: If you like this concept but find yourself in this situation:
1. Pickling is too slow.
2. The object I want to serialize is made up only of Python basic data types.
3. I don’t care if the saved information doesn’t work across Python versions.

Then you’re a prime candidate for the Marshal module.

[tags]Pickle, cPickle, Marshal, Object Serialization, Serialization, code sample[/tags]

Comments are closed.