Try using the bytearray type (Python 2.6 and later), it's much better suited to dealing with byte data. Your try block would be just:

ba = bytearray(fh.read())
for byte in ba:
    print byte & 1

or to create a list of results:

low_bit_list = [byte & 1 for byte in bytearray(fh.read())]

This works because when you index a bytearray you just get back an integer (0-255), whereas if you just read a byte from the file you get back a single character string and so need to use ord to convert it to an integer.


If your file is too big to comfortably hold in memory (though I'm guessing it isn't) then an mmap could be used to create the bytearray from a buffer:

import mmap
m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
ba = bytearray(m)
Answer from Scott Griffiths on Stack Overflow
🌐
Python Guides
pythonguides.com › read-a-binary-file-into-a-byte-array-in-python
Read a Binary File into a Byte Array in Python - Python Guides
March 19, 2025 - We can also modify the values of specific bytes by assigning new values to the corresponding indices. Check out How to Check the Length of an Array in Python · Binary files often contain structured data that needs to be interpreted correctly. Python provides the struct module to unpack binary data into meaningful values. Here’s an example: import struct with open("data.bin", 'rb') as file: # Read a 32-bit integer and a 64-bit float binary_data = file.read(12) # 4 bytes for integer + 8 bytes for float value1, value2 = struct.unpack('>if', binary_data) print(f"Value 1: {value1}, Value 2: {value2}")
Discussions

Python workflow for reading binary file into byte array
Is there a recommended way for reading and writing byte arrays in python inside Touch. I’m trying to understand how to use the Websocket DAT sendBinary method from code and hitting a more fundamental problem in that I can’t read a file off disk into a byte array. More on forum.derivative.ca
🌐 forum.derivative.ca
0
0
June 18, 2014
Whats a good way of writing an -int- as BYTES into a binary file (and later, reading it in too) ?
You might need the struct module to help you to get consistent sizing of the objects in binary format: https://docs.python.org/3/library/struct.html Python has "unlimited magnitude" integers - they just grow and grow to contain the required values, and different platforms (i.e. 32 vs 64 bit, intel vs. ARM etc.) can start with different "base" size integers. Using the struct module, you can make sure the appropriate representation is used. More on reddit.com
🌐 r/learnpython
7
9
February 7, 2022
python - Reading binary file and looping over each byte - Stack Overflow
In Python, how do I read in a binary file and loop over each byte of that file? More on stackoverflow.com
🌐 stackoverflow.com
How to Read Binary File in Python?
Learn how to read binary files in Python using built-in functions for efficient data processing and manipulation. More on accuweb.cloud
🌐 accuweb.cloud
1
May 2, 2024
🌐
Utk
marz.utk.edu › python › binary-files
Binary Files – Stephen Marz
The code above takes a bytes object, copies it into a byte array, changes the ‘s’ to a ‘z’, and copies it back. Notice that I had to use the ord(“z”), which is a special function that gives me the integer representation of a lowercase z. NOTE: Reading and writing to binary files uses the immutable bytes object.
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-binary-files-in-python
Reading Binary Files in Python - GeeksforGeeks
3 weeks ago - 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. ... readlines() method reads all lines into a list, and the for loop prints each line as ...
🌐
YouTube
youtube.com › programgpt
python read binary file into byte array - YouTube
Download this code from https://codegive.com Title: Reading Binary Files into Byte Arrays in Python: A Step-by-Step TutorialIn Python, working with binary fi...
Published   December 11, 2023
Views   99
🌐
W3docs
w3docs.com › python
Reading binary file and looping over each byte
Here is an example code snippet that demonstrates how to read a binary file and loop over each byte in Python: with open("file.bin", "rb") as binary_file: # Read the entire file into a byte array byte_array = binary_file.read() # Loop through ...
Find elsewhere
🌐
Fedingo
fedingo.com › home › how to read binary file in python
How to Read Binary File in Python - Fedingo
July 23, 2025 - In such cases you can easily do this using list() function as shown below. file = open("/home/ubuntu/data.bin","rb") arr=list(file.read(4)) print(arr) file.close() In the above code, we open the file in binary mode to read.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 515440 › reading-an-entire-binary-file
python - Reading an entire binary file [SOLVED] | DaniWeb
January 22, 2018 - Okay. I just found bytearray() which has accomplished my goals by: with open("portrait1.dng", "rb") as binaryfile : myArr = bytearray(binaryfile.read()) with open("readfile.raw", "wb") as newFile: newFile.write(myArr)
🌐
TouchDesigner
forum.derivative.ca › beginners
Python workflow for reading binary file into byte array - Beginners - TouchDesigner forum
June 18, 2014 - Is there a recommended way for reading and writing byte arrays in python inside Touch. I’m trying to understand how to use the Websocket DAT sendBinary method from code and hitting a more fundamental problem in that I can’t read a file off disk into a byte array.
🌐
Scaler
scaler.com › home › topics › reading binary files in python
Reading binary files in Python - Scaler Topics
February 26, 2024 - Create a byte array using the array module, specifying the 'B' type code for unsigned bytes. Read the binary data into this byte array using the fromfile() method, and you're all set to manipulate the data with ease.
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.

🌐
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 - 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.
🌐
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.
🌐
Linux Hint
linuxhint.com › read-binary-files-in-python
How to Read Binary Files in Python – Linux Hint
# Open a file handler to create a binary file file_handler = open("string.bin", "wb") # Add two lines of text in the binary file file_handler.write(b"Welcome to LinuxHint.\nLearn Python Programming.") # Close the file handler file_handler.close() # Open a file handler to create a binary file file=open("number_list.bin","wb") # Declare a list of numeric values numbers=[10,30,45,60,70,85,99] # Convert the list to array barray=bytearray(numbers) # Write array into the file file.write(barray) file.close()
🌐
Accuweb
accuweb.cloud › home › how to read binary file in python?
How to Read Binary File in Python?
May 2, 2024 - Binary files often contain structured fields like integers and floats. Python’s struct module converts raw bytes into Python values.
🌐
LinuxQuestions.org
linuxquestions.org › questions › linux-newbie-8 › python-read-binary-file-into-array-4175547091
python read binary file into array
hello pros! im quite a newbie in python. please help me out! so i have a hex file, that is about 2821 sector size. i want to create an array for every
🌐
IT trip
en.ittrip.xyz › python
Mastering Byte Arrays and Binary Files in Python: A Complete Guide | IT trip
November 4, 2023 - To convert a byte array to a binary file, you write the byte array to the file as shown above. Conversely, to convert a binary file to a byte array, you read the binary file and convert the bytes object to a bytearray object.