Pete’s pickled Python pecked a pick of pickled peppers

Yesterday we discovered pickling in python….

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.

A self-referencing list is stored:

import pickle

data = {'a': apple,'b': bat,'c': None}

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data, output)

output.close()

The following example reads the resulting pickled data. When reading a pickle-containing file, you should open the file in binary mode because you can’t be sure if the ASCII or binary format was used.

import pickle

pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)

pkl_file.close()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s