Skip to content

Computer Science · Ch 2 — File Handling in Python

The Pickle Module

2.8

The Pickle Module

The Pickle Module

Python treats everything as an object — lists, tuples, dictionaries, and even custom data structures are all objects. During a program's execution, you often need to save the current state of these objects so you can restore them later. Think of a video game: when you pause and close it, the program should be able to store the current state of the game — including your current level/stage, your score, and so on — as a Python object, so it can be restored later. Likewise, you may want to store a Python dictionary as an object, to be able to retrieve it in a future session.

To save any object structure along with its data, Python provides the Pickle module. The name comes from the food preservation method — pickling stores food items in a solution to increase their shelf life, i.e., preserving them for later consumption. In programming, pickling means serialization: transforming data or an object in memory (RAM) into a stream of bytes called a byte stream. This byte stream can then be stored in a binary file, stored in a database, or sent over a network. The reverse process — converting the byte stream back into a Python object — is called de-serialization or unpickling.

Important

The pickle module works exclusively with binary files. You do not write or read data — you dump and load it.

Before using pickle, you must import it:

import pickle

The module provides two main methods: …