How To Create A Binary File In Python

In this tutorial, we will learn how to create a binary file using Python. Binary files can be used for storing data in a compact and more efficient format.

They are especially useful when working with large amounts of data or when you need to store information that cannot be easily represented as text. With Python, you can easily create, read, and write binary files using the built-in functions.

Step 1: Opening a File in Binary Mode

The first step in creating a binary file is to open a new file in binary mode. To do this, you can use the open() function with the 'wb' mode:

The 'wb' mode indicates that the file is being opened for writing in binary mode. Note that if the file already exists, its contents will be overwritten.

Step 2: Writing Data to the Binary File

Next, you need to write the data to the binary file. You can do this using the write() method, but first, you have to convert the data to a binary format. Python provides several methods for converting data to binary, one of which is the pickle module.

Here’s an example of how to use the pickle module to write a list of integers to a binary file:

In this example, we first import the pickle module and then use the dump() method to write the list of integers (data) to the binary file (file). Finally, we close the file using the close() method.

Step 3: Reading Data from the Binary File

To read the data from the binary file, you need to open the file in binary read mode ('rb'). Then, you can use the load() method from the pickle module to extract the data:

In this example, we first open the binary file in read mode and then use the load() method to extract the data into a new variable loaded_data. After closing the file, we print the loaded data to the console.

Full Example

Here’s the complete code for creating, writing, and reading a binary file using Python:


[1, 2, 3, 4, 5]


In this tutorial, we learned how to create a binary file in Python using the open() function, the pickle module, and the write() and load() methods. By following these steps, you can easily create, write, and read binary files to store and process data more efficiently in your Python programs.