Read the binary file content like this:

with open(fileName, mode='rb') as file: # b is important -> binary
    fileContent = file.read()

then "unpack" binary data using struct.unpack:

The start bytes: struct.unpack("iiiii", fileContent[:20])

The body: ignore the heading bytes and the trailing byte (= 24); The remaining part forms the body, to know the number of bytes in the body do an integer division by 4; The obtained quotient is multiplied by the string 'i' to create the correct format for the unpack method:

struct.unpack("i" * ((len(fileContent) -24) // 4), fileContent[20:-4])

The end byte: struct.unpack("i", fileContent[-4:])

Answer from gecco on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ reading-binary-files-in-python
Reading Binary Files in Python - GeeksforGeeks
July 1, 2026 - Each element in the list represents one line from the binary file. ... readlines() method reads all lines into a list, and the for loop prints each line as a bytes object.
๐ŸŒ
Fedingo
fedingo.com โ€บ home โ€บ how to read binary file in python
How to Read Binary File in Python - Fedingo
July 23, 2025 - In the above code, we open the file in binary mode to read. Then use read function to read the first 4 bytes. We pass it to list() function to convert the string into an array. Here is the output of the above code ...
๐ŸŒ
Python Guides
pythonguides.com โ€บ python-read-a-binary-file
How to Read a Binary File in Python
November 4, 2025 - Another efficient way to read binary files in Python is to use the readinto() method. This method reads bytes directly into a pre-allocated buffer, which can be a bytearray or a memoryview.
๐ŸŒ
Linux Hint
linuxhint.com โ€บ read-binary-files-in-python
How to Read Binary Files in Python โ€“ Linux Hint
You can read the particular number of bytes or the full content of the binary file at a time. Create a python file with the following script. The open() function has used to open the string.bin for reading. The read() function has been used to read 7 characters from the file in each iteration of while loop and print.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ reading-binary-files-in-python
Reading binary files in Python - Python Morsels
May 16, 2022 - Repeatedly reading data within a while loop is a pretty good use case for an assignment expression. It may look a little bit weird, but it does save us a few lines of code. The walrus operator was added in Python 3.8. When you read a binary file in Python, you'll get back bytes.
Top answer
1 of 13
494

Python >= 3.8

Thanks to the walrus operator (:=) the solution is quite short. We read bytes objects from the file and assign them to the variable byte

with open("myfile", "rb") as f:
    while (byte := f.read(1)):
        # Do stuff with byte.

Python >= 3

In older Python 3 versions, we get have to use a slightly more verbose way:

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != b"":
        # Do stuff with byte.
        byte = f.read(1)

Or as benhoyt says, skip the not equal and take advantage of the fact that b"" evaluates to false. This makes the code compatible between 2.6 and 3.x without any changes. It would also save you from changing the condition if you go from byte mode to text or the reverse.

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte:
        # Do stuff with byte.
        byte = f.read(1)

Python >= 2.5

In Python 2, it's a bit different. Here we don't get bytes objects, but raw characters:

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte != "":
        # Do stuff with byte.
        byte = f.read(1)

Note that the with statement is not available in versions of Python below 2.5. To use it in v 2.5 you'll need to import it:

from __future__ import with_statement

In 2.6 this is not needed.

Python 2.4 and Earlier

f = open("myfile", "rb")
try:
    byte = f.read(1)
    while byte != "":
        # Do stuff with byte.
        byte = f.read(1)
finally:
    f.close()
2 of 13
194

This generator yields bytes from a file, reading the file in chunks:

def bytes_from_file(filename, chunksize=8192):
    with open(filename, "rb") as f:
        while True:
            chunk = f.read(chunksize)
            if chunk:
                for b in chunk:
                    yield b
            else:
                break

# example:
for b in bytes_from_file('filename'):
    do_stuff_with(b)

See the Python documentation for information on iterators and generators.

Top answer
1 of 6
8

for rec in inh: reads one line at a time -- not what you want for a binary file. Read 4 bytes at a time (with a while loop and inh.read(4)) instead (or read everything into memory with a single .read() call, then unpack successive 4-byte slices). The second approach is simplest and most practical as long as the amount of data involved isn't huge:

import struct
with open('test.bin', 'rb') as inh:
    indata = inh.read()
for i in range(0, len(data), 4):
    pos = struct.unpack('i', data[i:i+4])  
    print(pos)  

If you do fear potentially huge amounts of data (which would take more memory than you have available), a simple generator offers an elegant alternative:

import struct
def by4(f):
    rec = 'x'  # placeholder for the `while`
    while rec:
        rec = f.read(4)
        if rec: yield rec           
with open('test.bin', 'rb') as inh:
    for rec in by4(inh):
        pos = struct.unpack('i', rec)  
        print(pos)  

A key advantage to this second approach is that the by4 generator can easily be tweaked (while maintaining the specs: return a binary file's data 4 bytes at a time) to use a different implementation strategy for buffering, all the way to the first approach (read everything then parcel it out) which can be seen as "infinite buffering" and coded:

def by4(f):
    data = inf.read()
    for i in range(0, len(data), 4):
        yield data[i:i+4]

while leaving the "application logic" (what to do with that stream of 4-byte chunks) intact and independent of the I/O layer (which gets encapsulated within the generator).

2 of 6
5

I think "for rec in inh" is supposed to read 'lines', not bytes. What you want is:

while True:
    rec = inh.read(4) # Or inh.read(struct.calcsize('i'))
    if len(rec) != 4:
        break
    (pos,) = struct.unpack('i', rec)
    print pos

Or as others have mentioned:

while True:
    try:
        (pos,) = struct.unpack_from('i', inh)
    except (some_exception...):
        break
Find elsewhere
Top answer
1 of 1
6

No, you can't use a TextIOWrapper() object because it'll read from the underlying buffer in larger blocks, not just in lines, so yes, it'll try to decode binary data past than first line. You can't prevent this.

For a single line of text using \n line delimiters, you really don't need to use TextIOWrapper(). Binary files still support line-by-line reading, where file.readline() will give you the binary data up to the next \n byte. Just open the file as binary, and read one line.

Valid UTF-16 data will always have an even length. But because UTF-16 comes in two flavours, big endian and little endian byte orders, you'll need to check how much data was read to see what byte order was used, in order to conditionally read a single byte that should be part of that first line of data. If UTF-16 little-endian was used, you are guaranteed to have read an odd number of bytes, as newlines are encoded to 0a 00 rather than 00 0a and the .readline() call will have left the single 00 byte in the file stream. In that case, just read one more byte and add it to the first line data before decoding:

with open(filename, 'rb') as binfile:
    firstline = binfile.readline()
    if len(firstline) % 2:
        # little-endian UTF-16, add one more byte
        firstline += binfile.read(1)
    text = firstline.decode('utf-16')

    # read binary data from the file

A demo with io.BytesIO() where we first write UTF-16 little-endian data (with the BOM to indicate the byte order for the decoder), with the text followed by two low-surrogate sequences that would cause a UTF-16 decoding error to stand for 'binary data', after which we read the text and data again:

>>> import io, codecs
>>> from pprint import pprint
>>> binfile = io.BytesIO()
>>> utf16le_wrapper = io.TextIOWrapper(binfile, encoding='utf-16-le', write_through=True)
>>> utf16le_wrapper.write('\ufeff')  # write the UTF-16 BOM manually, as the -le and -be variants won't include this
1
>>> utf16le_wrapper.write('The quick brown ๐ŸฆŠ jumps over the lazy ๐Ÿ•\n')
40
>>> binfile.write(b'\xDF\xFF\xDF\xFF')  # binary data, guaranteed to not decode as UTF-16
4
>>> binfile.flush()  # flush and seek back to start to move to reading
>>> binfile.seek(0)
0
>>> firstline = binfile.readline()  # read that first line
>>> len(firstline) % 2              # confirm we read an odd number of bytes
1
>>> firstline += binfile.read(1)    # add the expected null byte
>>> pprint(firstline)               # peek at the UTF-16 data we read
(b'\xff\xfeT\x00h\x00e\x00 \x00q\x00u\x00i\x00c\x00k\x00 \x00b\x00r\x00o\x00'
 b'w\x00n\x00 \x00>\xd8\x8a\xdd \x00j\x00u\x00m\x00p\x00s\x00 \x00o\x00v\x00'
 b'e\x00r\x00 \x00t\x00h\x00e\x00 \x00l\x00a\x00z\x00y\x00 \x00=\xd8\x15\xdc'
 b'\n\x00')
>>> print(firstline.decode('utf-16'))  # bom included, so the decoder detects LE vs BE
The quick brown ๐ŸฆŠ jumps over the lazy ๐Ÿ•

>>> binfile.read()
b'\xdf\xff\xdf\xff'

Any alternative implementations that still can use TextIOWrapper() would require an intermediate wrapper to sit between the binary file and the TextIOWrapper() instance to prevent TextIOWrapper() to read too far, and this would get complex fast and would require the wrapper have knowledge of the codec used anyway. For a single line of text, that's just not worth the effort required.

๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ read binary files in python
How to Read Binary File in Python | Delft Stack
March 13, 2025 - The most straightforward way to read a binary file in Python is by using the built-in open() function. This function allows you to open a file in binary mode, enabling you to read its contents byte by byte.
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python read binary file
Python Read Binary File โ€“ Be on the Right Side of Change
April 10, 2022 - Line [3] creates a bytearray of the variable nums and assigns this value to the variable array. The bytearray() method returns a bytearray object which is an array of bytes. Line [4] writes the variable array to the file opened earlier. Line [5] closes the previously opened file. Reading from a binary file is similar to the steps taken above.
๐ŸŒ
ThePythonGuru
thepythonguru.com โ€บ python-how-to-read-and-write-files
Python: How to read and write files - ThePythonGuru.com
January 7, 2020 - Reading and writing binary file is done by appending b to the mode string. In Python 3, the binary data is represented using a special type called bytes.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-read-a-binary-file-in-Python-3
How to read a binary file in Python 3 - Quora
Answer (1 of 3): You is open with the โ€˜rbโ€™ mode, and then use read(โ€ฆ). Donโ€™t use readline(..), readlines(โ€ฆ) to try to read the file ( as it will look for end of lines) and donโ€™t try to use a for loop either, as that also works with end of lines. an example would be : [code]with ...
๐ŸŒ
YouTube
youtube.com โ€บ python morsels
Reading binary files in Python - YouTube
How can you read binary files in Python? And how can you read very large binary files in small chunks?Read an article version of this video at https://pym.de...
Published: October 5, 2022
Views: 5K
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ python โ€บ python-read-write-file
Python - Read and Write Files
File object includes the following ... starting from the current position. readline(): reads the characters starting from the current reading position up to a newline character. readlines(): reads all lines until the end ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ read-a-file-line-by-line-in-python
Read a file line by line in Python - GeeksforGeeks
May 21, 2025 - This final way of reading a file line-by-line includes iterating over a file object in a loop. In doing this we are taking advantage of a built-in Python function that allows us to iterate over the file object implicitly using a for loop in combination with using the iterable object.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 74222526 โ€บ read-a-entire-line-in-a-binary-file-which-consists-of-multiple-lines-in-python
cryptography - read a entire line in a binary file which consists of multiple lines in python - Stack Overflow
If you really want to look for a new line character in a binary file then you can just iterate over a file object but if there is none, it will return the whole file content: ... Copyimport io import os SIZE = 1024 def main(): buf = ...
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 515440 โ€บ reading-an-entire-binary-file
python - Reading an entire binary file [SOLVED] | DaniWeb
January 22, 2018 - is there a better way to read the file? like portion by portion perhaps? how is that achieved? because i dont really need the write, the write is just for me to see that the file is wholly read. i need the read for other processes. ... with open("portrait1.dng", "rb") as binaryfile : with open("readfile.raw", "wb") as newFile: while True: chunk = binaryfile.read(4096) if not chunk: break newFile.write(binascii.hexlify(chunk))
๐ŸŒ
Bestprog
bestprog.net โ€บ en โ€บ 2020 โ€บ 04 โ€บ 30 โ€บ python-binary-files-examples-of-working-with-binary-files
Python. Binary files. Examples of working with binary files | BestProg
April 30, 2020 - Open file for writing f = open('myfile5.bin', 'wb') # 2.2. Tuple bypass cycle for item in T: bt = (item + '\n').encode() # convert (str + '\n') => bytes f.write(bt) # write bt to file # 2.3. Close file f.close(); # 3. Read tuple from binary file 'myfile5.bin' # 3.1. Open file for reading f = open('myfile5.bin', 'rb') # 3.2. A new tuple T2 = () # 3.3. Read data from file for line in f: s = line.decode() # convert bytes=>str s = s[:-1] # Remove the last character T2 = T2 + (s,) # Add string s to tuple # 3.4.
๐ŸŒ
Utk
marz.utk.edu โ€บ python โ€บ binary-files
Binary Files โ€“ Stephen Marz
If we want to open the file as a sequence of 0s and 1s (binary) instead of a sequence of characters (text), we can add a โ€œbโ€ to the mode, which stands for binary. For example, f = open("myfile.bin", "rb") will open the file myfile.bin for reading as a binary file.