How to write binary data to a file using Python?


It is a common and routine task in Python; the act of writing binary data to a file when you need to save non-textual data such as images, audio files, or serialized objects. In this article, we will explore various ways how you can write binary data to a file using Python and provide you with code examples followed by comprehensive explanations to help you grasp the concept.

To write binary data to a file in Python, you can follow these steps:

Open the File in Binary Mode

First, you should proceed to open the file in binary mode using the open() function. When opening the file, the mode is declared as 'wb', which stands for write in binary mode. This mode makes sure that the data you write to the file will be treated as binary data.

file_path = "path/to/file.bin"

with open(file_path, "wb") as file:
    # Write binary data to the file
    # ...

In the above code, file_path points to the path to the file you want to write to. The ‘with statement’ is used to ensure that the file is properly closed after writing.

Write the Binary Data to the File

After the file is opened in binary mode, you make use of the write() method to write binary data to the file. The write() method accepts a bytes object as an argument, which contains the binary data you want to write.

file_path = "path/to/file.bin"

with open(file_path, "wb") as file:
    binary_data = b"\x48\x65\x6C\x6C\x6F"  
# Example binary data
    file.write(binary_data)

In the code given above, binary_data is a bytes object that comprises of the binary data you wish to write. Here, we are writing the ASCII representation of the string "Hello" to the file.

Close the File

After writing the binary data is finished, it is important to close the file to release system resources. The ‘with statement’ takes care of closing the file for you, but if you are not using it, ensure to that the close() method is called on the file object.

file_path = "path/to/file.bin"
file = open(file_path, "wb")

# Write binary data to the file
# ...

file.close()

In the above code, file.close() is utilized to close the file after writing the binary data.

Example

In this current example, we first define the file_path variable as the path to the file where we wish to write the binary data. Then, we make use of the open() function with the mode set to 'wb' to open the file in binary write mode. Within the ‘with block’, we generate a bytearray object named binary_data, which contains the binary data we need to write. In this instance, we have a sequence of four bytes with hexadecimal values. Lastly, we use the write() method to write the binary data to the file.

file_path = "path/to/file.bin"

with open(file_path, "wb") as file:
    binary_data = bytearray([0xFF, 0x00, 0x7F, 0x80])  
    # Example binary data as a bytearray
    file.write(binary_data)

Example

In this code example, we show how to write binary data utilizing the struct module; it provides functions for packing and unpacking binary data. We start when the struct module is imported. Then, we provide the file_path variable with the path to the file. Inside the ‘with block’, two variables, value1 and value2 are defined, which represent the data we want to write. We make use of the struct.pack() function to pack the values into binary data. In this case, we pack an integer ("i") and a float ("f"). We concatenate the resulting binary data using the + operator and write it to the file using the write() method.

import struct

file_path = "path/to/file.bin"

with open(file_path, "wb") as file:
    value1 = 123
    value2 = 3.14
    binary_data = struct.pack("i", value1) + 
struct.pack("f", value2)
    file.write(binary_data)

Example

Here, we first import the array module. Then, we define the file_path variable as the path to the file where we want to write the binary data. We generate an array object named data and assign it a sequence of unsigned byte values. Within the with block, the file is opened in binary write mode and the write() method is used to write the binary data to the file. We convert the array to bytes using the tobytes() method before writing it.

import array
file_path = "path/to/file.bin"

data = array.array("B", [10, 20, 30, 40, 50])  
# Example binary data as an array

with open(file_path, "wb") as file:
    file.write(data.tobytes())

Example

In the last example, we demonstrate yet another technique of using the struct module to pack the binary data. First, the struct module is imported. Then, file_path variable is defined as the path to the file. We have two variables, value1 and value2, to point to the data we want to write. We use the struct.pack() function to pack the values into binary data. In this case, we pack an integer ("i") and a float ("f"). The resulting binary data is loaded in the data variable. Within the ‘with block’, the file is opened in binary write mode and the write() method is used to write the binary data to the file.

import struct

file_path = "path/to/file.bin"

value1 = 123
value2 = 3.14

data = struct.pack("i f", value1, value2)  
# Example binary data as a packed struct
with open(file_path, "wb") as file:
    file.write(data)

In this article, as you have seen by now, we have explored several ways how you can write binary data to a file using Python. We discussed the steps involved, including opening the file in binary mode, writing the binary data, and closing the file. By following these steps diligently and using the appropriate mode and methods, you can effectively and efficiently write binary data to a file in Python. It does not matter if you are working with images, audio files, or any other binary data, mastering this skill will empower you to handle non-textual data elegantly in your Python programs.

Updated on: 25-Jul-2023

19K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements