python
binary-files
file-io
looping
duplicate-content

Python read binary file and iterate over each byte

Codemia Knowledge Hub ·

To loop over each byte of a binary file in Python, open it in rb mode and iterate over the bytes object you read. Each iteration yields an integer from 0 to 255, not a one-character string. For large files, read in chunks so memory use stays predictable.

Open the file in binary mode

Always use rb. Text mode tries to decode the file and can change newline handling, which corrupts raw binary data.

python
1with open("sample.bin", "rb") as handle:
2    data = handle.read()
3
4print(type(data))   # <class 'bytes'>
5print(len(data))

bytes is an immutable sequence of integers from 0 to 255, which is why iterating over it yields integers.

Loop over each byte

python
with open("sample.bin", "rb") as handle:
    for byte_value in handle.read():
        print(byte_value)

This prints decimal values such as 137, 80 or 255, which is often enough for checksum logic, simple scanners or quick debugging of a file header. If you need a one-byte bytes object instead of an integer, slice: data[i:i+1].

For a hex view with offsets, use enumerate() and format the values:

python
with open("sample.bin", "rb") as handle:
    for offset, byte_value in enumerate(handle.read()):
        print(f"{offset:04x}: {byte_value:02x}")

This helps when inspecting file signatures, since many binary formats start with a recognizable magic number.

Read large files in chunks

handle.read() loads the whole file, which is fine for small files but wasteful for multi-gigabyte ones. A chunked loop still visits every byte without holding the entire file in memory:

python
1chunk_size = 4096
2
3with open("sample.bin", "rb") as handle:
4    while True:
5        chunk = handle.read(chunk_size)
6        if not chunk:
7            break
8
9        for byte_value in chunk:
10            pass  # process each byte here

This is the usual production approach.

Interpret bytes with struct

Many binary formats store multi-byte integers, floats or fixed headers. Once you know the layout, the struct module decodes them:

python
1import struct
2
3with open("numbers.bin", "rb") as handle:
4    header = handle.read(4)
5    value = struct.unpack("<I", header)[0]
6    print(value)

"<I" means a little-endian unsigned 32-bit integer. For big-endian data, start the format string with ">" instead. The byte loop gives you the lowest-level access, and struct turns those bytes into meaningful values.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
There is a whole course on this

Basis Lab has written “Bytes, Text and File Formats”, a course that teaches this from the ground up rather than answering the single question. It is a separate product from the same team and the course is free to read.

Read the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms