Reading Binary Files in Python

Last Updated : 1 Jul, 2026

Reading a binary file involves opening the file in binary mode and accessing its contents as bytes instead of text. This is commonly used when working with files such as images, audio files, videos, PDFs or other non-text data.

Python
with open("sample.bin", "rb") as file:
    data = file.read()
    print(data)

Explanation: file is opened using "rb" mode, where r stands for read and b stands for binary. The read() method retrieves the file contents as a sequence of bytes

Binary File Modes

Python provides different modes for reading and writing binary files:

  • rb: Opens a file for reading binary data.
  • wb: Opens a file for writing binary data. If the file already exists, its contents are overwritten.
  • ab: Opens a file for appending binary data at the end without removing existing content.

Opening a Binary File

To read data from a binary file, the file must be opened in read binary mode ("rb"). In this mode, Python reads the file as raw bytes instead of converting the contents into text.

Python
file = open("file_name", "rb")

After opening the file, you can use methods such as read() and readlines() to access its contents.

Using read()

The read() method reads the entire binary file and returns its contents as a bytes object.

Python
f = open('example.bin', 'rb')
data = f.read()
print(data)
f.close()

Output

b'Hello World'

Explanation:

  • file is opened in binary read mode ("rb"). The read() method reads all bytes from the file and stores them in the variable data.
  • Since the content is read as bytes, the output is displayed with a b prefix. Finally, close() is used to close the file.

Using readlines()

The readlines() method reads the file line by line and returns a list of byte strings. Each element in the list represents one line from the binary file.

Python
with open('example.bin', 'rb') as f:
    lines = f.readlines()

    for line in lines:
        print(line)

Output

b'First Line\n'
b'Second Line\n'
b'Third Line\n'

Explanation:

  • file is opened using the with statement, which automatically closes the file after use.
  • readlines() method reads all lines into a list, and the for loop prints each line as a bytes object.

Reading Binary File in Chunks

For large binary files, reading the entire file at once may consume a lot of memory. In such cases, it is better to read the file in smaller chunks using read(size).

Python
chunk_size = 1024

with open('example.bin', 'rb') as f:
    while True:
        chunk = f.read(chunk_size)

        if not chunk:
            break
        print(chunk)

Output

b'...first 1024 bytes...'
b'...next 1024 bytes...'

Explanation:

  • The file is read in blocks of 1024 bytes. The loop continues reading chunks until no more data is available.
  • This approach is useful for processing large binary files efficiently without loading the entire file into memory.
Comment