Open a File in Binary Mode in Python
In Python, you can open a file in binary mode by using the built-in open()
function with the mode set to 'rb'
for reading, 'wb'
for writing, or 'ab'
for appending in binary format. This is useful when working with non-text files such as images, audio files, and other binary data.
Examples for Opening a File in Binary Mode
1. Reading a File in Binary Mode
To read a file in binary mode, use the rb
mode with the open()
function. This reads the file as bytes rather than a string.

main.py
# Open a file in binary read mode
with open("binary_file.bin", "rb") as file:
binary_data = file.read()
# Printing the binary content
print("Binary Data:", binary_data)
Explanation:
open("binary_file.bin", "rb")
: Opens the fileexample.bin
in binary read mode.file.read()
: Reads the entire content of the file in bytes.- The
with
statement ensures that the file is properly closed after reading.
Output:

2. Writing to a File in Binary Mode
To write binary data to a file, use the wb
mode. This is useful when working with encoded data or file transfers.
main.py
# Binary data to write
binary_content = b"Hello, Binary World!"
# Open a file in binary write mode
with open("output.bin", "wb") as file:
file.write(binary_content)
print("Binary data written successfully.")
Explanation:
binary_content = b"Hello, Binary World!"
: Defines binary data using theb''
prefix.open("output.bin", "wb")
: Opens the file in binary write mode.file.write(binary_content)
: Writes the binary content to the file.
Output:


3. Appending Data in Binary Mode
Use ab
mode to append binary data to an existing file.
We will append new data to the output.bin file that is already created in the previous example.
main.py
# Binary data to append
additional_data = b"\nAppending more binary data."
# Open a file in binary append mode
with open("output.bin", "ab") as file:
file.write(additional_data)
print("Binary data appended successfully.")
Explanation:
additional_data
: Defines binary data to append.open("output.bin", "ab")
: Opens the file in binary append mode.file.write(additional_data)
: Appends the binary content to the file.
Output:


4. Reading a Binary File in Chunks
To handle large binary files efficiently, read them in chunks instead of loading them all at once.
main.py
# Open a file in binary read mode
with open("binary_file.bin", "rb") as file:
while chunk := file.read(10): # Read 10 bytes at a time
print(chunk)
Explanation:
file.read(10)
: Reads 10 bytes at a time.while chunk := file.read(10)
: Uses the walrus operator (:=
) to read chunks until the file ends.
Output:

Conclusion
In this tutorial, we covered multiple ways to open and manipulate binary files:
'rb'
: Opens a file for reading in binary mode.'wb'
: Opens a file for writing binary data.'ab'
: Appends binary data to an existing file.- Reading in Chunks: Helps process large files efficiently.