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()
Answer from Skurmedel on Stack Overflow
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.

🌐
Python Morsels
pythonmorsels.com › reading-binary-files-in-python
Reading binary files in Python - Python Morsels
May 16, 2022 - That library will do the work of decoding the bytes from your file into something that's easier to work with. For example, Python's ZipFile module can help us read data that's within a zip file:
Discussions

Python, how to read bytes from file and save it? - Stack Overflow
I want to read bytes from a file and then write those bytes to another file, and save that file. How do I do this? More on stackoverflow.com
🌐 stackoverflow.com
Fastest way to read bytes as a scalar?
You can use the struct (builtin) library to interpret 4 bytes as a 32-bit integer. You shouldn’t need numpy for this part at all - just open the file, read 4 bytes, and interpret it with struct. More on reddit.com
🌐 r/learnpython
23
3
March 10, 2021
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
How to read a file byte by byte in Python and how to print a bytelist as a binary? - Stack Overflow
I'm trying to read a file byte by byte, but I'm not sure how to do that. I'm trying to do it like that: file = open(filename, 'rb') while 1: byte = file.read(8) # Do something... So does tha... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python.org
discuss.python.org › python help
Read/write byte objects - Python Help - Discussions on Python.org
March 17, 2023 - I’m coding a file backup app and I’ve got the basics down, aside from the ‘engine’, so to speak. I’ve coded this: def read_write(source, target): rBytes = True with open(source, mode='rb') as read_file, open(target, mode='wb') as write_file: while rBytes: rBytes = read_file.read(1024) write_file.write(rBytes) … and it works.
🌐
Python
docs.python.org › 3 › library › io.html
io — Core tools for working with streams
Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-binary-files-in-python
Reading Binary Files in Python - GeeksforGeeks
3 weeks ago - 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 · Python provides different modes for reading and writing binary files:
🌐
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.
🌐
Real Python
realpython.com › python-bytes
Bytes Objects: Handling Binary Data in Python – Real Python
January 20, 2025 - Arguably, the most straightforward way to use two’s complement when reading or writing binary data in Python is to call an integer’s .to_bytes() and .from_bytes() methods with the signed parameter set to True:
Find elsewhere
🌐
Real Python
realpython.com › ref › builtin-types › bytes
bytes | Python’s Built-in Data Types – Real Python
You can use the bytes data type to efficiently handle this task: ... >>> with open('example.bin', 'rb') as file: ... data = file.read() ... print(data[:10]) ...
Top answer
1 of 4
161

Here's how to do it with the basic file operations in Python. This opens one file, reads the data into memory, then opens the second file and writes it out.

in_file = open("in-file", "rb") # opening for [r]eading as [b]inary
data = in_file.read() # if you only wanted to read 512 bytes, do .read(512)
in_file.close()

out_file = open("out-file", "wb") # open for [w]riting as [b]inary
out_file.write(data)
out_file.close()

We can do this more succinctly by using the with keyboard to handle closing the file.

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
    out_file.write(in_file.read())

If you don't want to store the entire file in memory, you can transfer it in pieces.

chunk_size = 4096 # 4 KiB

with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
    while True:
        chunk = in_file.read(chunk_size)
            
        if chunk == b"":
            break # end of file
            
        out_file.write(chunk)
2 of 4
19

In my examples I use the 'b' flag ('wb', 'rb') when opening the files because you said you wanted to read bytes. The 'b' flag tells Python not to interpret end-of-line characters which can differ between operating systems. If you are reading text, then omit the 'b' and use 'w' and 'r' respectively.

This reads the entire file in one chunk using the "simplest" Python code. The problem with this approach is that you could run out memory when reading a large file:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
ofile.write(ifile.read())
ofile.close()
ifile.close()

This example is refined to read 1MB chunks to ensure it works for files of any size without running out of memory:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
data = ifile.read(1024*1024)
while data:
    ofile.write(data)
    data = ifile.read(1024*1024)
ofile.close()
ifile.close()

This example is the same as above but leverages using with to create a context. The advantage of this approach is that the file is automatically closed when exiting the context:

with open(input_filename,'rb') as ifile:
    with open(output_filename, 'wb') as ofile:
        data = ifile.read(1024*1024)
        while data:
            ofile.write(data)
            data = ifile.read(1024*1024)

See the following:

  • Python open(): http://docs.python.org/library/functions.html#open
  • Python read(): http://docs.python.org/library/stdtypes.html#file.read
  • Python write(): http://docs.python.org/library/stdtypes.html#file.write
  • Dive into Python File Object Tutorial: http://diveintopython.net/file_handling/file_objects.html
🌐
Andrea Minini
andreaminini.net › computer-science › python › reading-a-file-byte-by-byte-in-python
Reading a File Byte by Byte in Python - Andrea Minini
In Python, you can open and read a file in chunks by specifying the number of bytes you want to read at a time using the read method.
🌐
Tutorialspoint
tutorialspoint.com › python › file_read.htm
Python File read() Method
The Python File read() method reads the contents of a file. This method reads the whole file, by default; and only specified bytes, if an optional argument is accepted. Even if the file contains more characters than the mentioned size, the remaining ...
🌐
Reddit
reddit.com › r/learnpython › fastest way to read bytes as a scalar?
r/learnpython on Reddit: Fastest way to read bytes as a scalar?
March 10, 2021 -

I'm reading in binary data from a file with:

data = np.fromfile(file,dtype='>b')
data
> array([ 5,  0,  0, ...,  2,  0, 99], dtype=int8)

This returns an array of int8. I'd like to read in, for example, the first 4 bytes and interpret these as an int32. I seem to have two options:

  1. np.frombuffer(data[0:4],dtype=np.int32)[0] index the only element of a length-1 array.

  2. data[0:4].view(dtype=np.int32)[0] index the only element of a length-1 array.

Is there a 3rd option that directly reads this in as an int? It's in a loop and I don't want the overhead of constructing an array each time, followed by indexing the 0th element of the array. This seems unnecessary. Can't I just create an np.int32 from the first 4 bytes?


Update: here are the runtimes for the various options after running through some of the data:

Method Time
int.from_bytes(data[idx:idx+4],byteorder='little',signed=False) 4.85s
struct.unpack('<i',data[idx:idx+4])[0] 12.5s
np.frombuffer(data[0:4],count=1,dtype=np.int32)[0] 31.3s
np.frombuffer(data[0:4],dtype=np.int32)[0](leaving out count=1) 21.8s
data[idx:idx+4].view(dtype=np.int32)[0] 16.6s

The first one is the clear winner.

🌐
TestDriven.io
testdriven.io › tips › 4a7f7213-7204-4418-9da3-7d0311afe1c1
Tips and Tricks - Using pathlib's read_bytes method in Python | TestDriven.io
Python tip: You can use read_bytes() (which handles the opening and closing of the file) from pathlib's Path to read bytes from a file instead of using with open(). Example: # pathlib import pathlib file_bytes = pathlib.Path("file.pdf").read_bytes() ...
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 515440 › reading-an-entire-binary-file
python - Reading an entire binary file [SOLVED] | DaniWeb
January 22, 2018 - If you must process in portions, keep your output file open once and append each processed chunk; repeatedly reopening with mode "wb" will overwrite earlier chunks and leave only the last block. For even lower overhead, consider readinto() with a preallocated bytearray or memoryview, or, for advanced use cases, memory mapping (mmap).
🌐
Accuweb
accuweb.cloud › home › how to read binary file in python?
How to Read Binary File in Python?
May 2, 2024 - Never use f.read() on multi-GB files. Use chunked reading or mmap. ... A) Endianness determines byte order in multi-byte values. Little-endian stores least significant byte first.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 182003 › beginner-how-do-i-read-in-one-bit-byte-at-a-time-from-a-file
python - Beginner: How do I read in one bit/byte ... | DaniWeb
The usual pattern is to read bytes in binary mode and unpack each byte into 8 bits. Also note that read() returns an empty string at EOF, so loops should terminate on '' to avoid hanging the interpreter, as you saw.
🌐
Programiz
programiz.com › python-programming › methods › built-in › bytes
Python bytes()
# convert string to bytes byte_message = bytes(message, 'utf-8') print(byte_message) # Output: b'Python is fun' ... bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256. If you want to use the mutable version, use the ...
🌐
Dataiku Community
community.dataiku.com › questions & discussions › using dataiku
Read a file line by line, in Python when read in as bytes — Dataiku Community
May 11, 2022 - line = data.read_line() cnt = 1 while line: print("Line {}: {}".format(cnt, line.strip())) line = data.readline() cnt += 1