How to Write Bytes to File in Python?

Recently I faced a real issue while working on a project that required storing user-uploaded images in a database, which led me to explore the best practices to accomplish this task. In this tutorial, I will explain how to write bytes to file in Python with detailed examples.

Open a File in Binary Write Mode

To write bytes to a file, you need to open the file in binary write mode. In Python, this is done using the open() function with the mode 'wb'. The 'wb' mode stands for “write binary.”

Read How to Read Large CSV Files in Python?

Example: Write Binary Data to a File

Let’s start with a simple example. Suppose we have a list of bytes representing some binary data, and we want to write this data to a file named data.bin.

# Sample binary data
binary_data = b'\xDE\xAD\xBE\xEF'

# Open a file in binary write mode
with open('data.bin', 'wb') as file:
    file.write(binary_data)

print("Data written to file successfully.")

Output:

Data written to file successfully.

I executed the above and added the screenshot below.

Write Bytes to File in Python

In this example, we use the with statement to open the file, ensuring it is properly closed after writing. The write() method is then used to write the binary data to the file.

Check out How to Create a Python File in Terminal?

Write a List of Numbers as Bytes

Often, you may need to write a list of numbers in a binary file. To achieve this, you can use the struct module, which provides functions to convert Python values to C structs represented as Python bytes objects.

Example: Write a List of Integers

Suppose we have a list of integers that we want to write to a binary file. Here’s how you can do it:

import struct

# List of integers
numbers = [1, 2, 3, 4, 5]

# Convert the list of integers to bytes
byte_data = struct.pack('5i', *numbers)

# Write the bytes to a binary file
with open('numbers.bin', 'wb') as file:
    file.write(byte_data)

print("List of integers written to file successfully.")

Output:

List of integers written to file successfully.

I executed the above and added the screenshot below.

How to Write Bytes to File in Python

In this example, struct.pack('5i', *numbers) converts the list of integers into a bytes object. The format string '5i' indicates that we are packing five integers.

Read How to Replace a Specific Line in a File Using Python?

Handle Large Binary Files

When dealing with large binary files, it is efficient to write data in chunks rather than loading the entire file into memory. This approach is particularly useful for applications like video processing or large dataset handling.

Example: Write Data in Chunks

Here’s an example of how to write large binary data in chunks:

chunk_size = 1024  # 1KB

# Generate a large amount of binary data for demonstration
large_data = b'\x00' * (10 * chunk_size)  # 10KB of data

# Write the data to a binary file in chunks
with open('large_data.bin', 'wb') as file:
    for i in range(0, len(large_data), chunk_size):
        file.write(large_data[i:i + chunk_size])

print("Large data written to file in chunks successfully.")

Output:

Large data written to file in chunks successfully.

I executed the above and added the screenshot below.

Write Bytes to File in Python Chunks data

In this example, we write the binary data in chunks of 1KB to the file large_data.bin. This method ensures efficient memory usage.

Check out How to Call a Function from Another File in Python?

Read Binary Files

To verify the data written to a binary file, you can read the file back and check its contents. Here’s how you can read a binary file in Python:

Example: Read Binary Data

# Read the binary data from the file
with open('data.bin', 'rb') as file:
    binary_content = file.read()

print("Binary data read from file:", binary_content)

In this example, we open the file data.bin in binary read mode ('rb') and use the read() method to read the binary data.

Read How to Read an Excel File in Python?

Conclusion

In this article, I helped you learn how to write bytes to file in Python. I explained how to open a file in binary write mode, write a list of numbers as bytes, handle large binary files, and read binary files.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.