Class XII: Python Data File Handling 11

Python Binary File Handling

Binary File Operations

If we wish to write a structure such as list or dictionary to a file and read it subsequently. We need to use the Python module pickle.

Picking refers to the process of converting structure to a byte stream before writing to the file. While reading the contents of the file a reverse process called Unpickling is used to convert the byte stream back to the original structure.

We know that the methods provided in python for writing/reading a file work with string parameter. So when we want to work on a binary file, the conversion of data at the time of reading as well as writing is required.

“Pickle” method can be used to store any kind of object in a file as it allows us to store Python objects with their structures. So for storing data in binary format we will use “pickle” method.

First, we need to import the module. It provides two main methods for the purpose- dump and load.

import pickle


For creation of a binary file we will use pickle.dump() to write object in the file, which is opened in binary access mode.

Syntax of dump() method:

Once data is stored in the file using dump(), then we can read the stored data using pickle.load() method.

Syntax of load() method:

We need to call load() each time dump() is called.