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: Complete Python Programming Course & Exercises

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.

1
2
3
4
5
6
7
import pickle

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

fileObj = open('data.obj', 'wb')
pickle.dump(exampleObj,fileObj)
fileObj.close()

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).

1
2
3
4
5
6
import pickle   

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

This will show you the previously saved object:

python pickle

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

Try the exercises below:

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