Pickle can be used to serialize and deserialize objects. A seralized object can be saved and loaded from the disk. Pickling is a method to convert an object (list, dict, etc) to a file and vice versa.

The idea is to save one or more objects in one script and load them in another. You can also use it to save program or game states.

We will save and load using a binary file, as this saves disk space.

Related course: Object Oriented Programming with Python

Serialize object

To use pickling, import the pickle module.
Create an object and seralize it. Then write it to a file using a file object.

import pickle

exampleObj = {'Python':3,'KDE':5,'Windows':10}

fileObj = open('data.obj', 'wb')

Deserialize object

Now that the object is saved to a file, you can load it (unpickle it). In the example below we load the object from the file.

Load the pickle module, open then the file for reading then load the data with pickle.load(). You can load it into any variable you want, but I’ve used the same name for convenience (exampleObj).

import pickle   

fileObj = open('data.obj', 'rb')
exampleObj = pickle.load(fileObj)

This will show you the previously saved object:

python pickle


Try the exercises below:

  1. Save and load an object from a file
  2. Try loading more than one object from a file