Sub topic 10
Binary files and reading in chunks
This chapter assumes you can open text files with open() and with, you know the difference between str and bytes, and you can use try/except. It covers opening files in binary mode, what changes compared with text mode, and how to process files of any size in fixed-size pieces.
What binary mode changes
In text mode, Python decodes the bytes on disk into str objects using an encoding. It also translates newlines. In binary mode it does neither. You get the raw bytes exactly as stored, and you must write bytes, bytearray, or another bytes-like object.
Use binary mode for anything that is not text: images, audio, archives, PDFs, executables, and files in a custom format. It is also the right choice when you want to copy a file without interpreting its content, even if that file happens to be text.
You select binary mode by adding b to the mode string.
| Mode | Meaning | If the file exists | If the file is missing |
|---|---|---|---|
| `rb` | Read bytes | Opens it | `FileNotFoundError` |
| `wb` | Write bytes | Truncates it to zero length | Creates it |
| `ab` | Append bytes | Keeps content, writes at the end | Creates it |
| `xb` | Exclusive create | `FileExistsError` | Creates it |
| `rb+` | Read and write bytes | Keeps content | `FileNotFoundError` |
The object returned by open(..., "rb") is a BufferedReader. For wb it is a BufferedWriter. Both keep an internal buffer, so many small reads and writes do not each cost a system call.
Bytes are not strings
Reading from a binary file gives you bytes. Indexing a bytes object returns an integer, while slicing returns another bytes object.
signature = bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
with open("sig.bin", "wb") as f:
count = f.write(signature)
print(count)
with open("sig.bin", "rb") as f:
head = f.read(4)
print(head)
print(head[0])
print(head[1:4])This prints 8, then b'\x89PNG', then 137, then b'PNG'. The first four bytes of every PNG image look like this, which is why programs can identify file types by reading only a few bytes from the start.
write() returns the number of bytes written. For a buffered binary file this is normally the full length of what you passed.
Mixing up text and binary
Two errors are common when the two modes are mixed. Both are raised immediately, so they are easy to spot.
with open("out.bin", "wb") as f:
try:
f.write("text")
except TypeError as error:
print(error)
try:
open("out.bin", "wb", encoding="utf-8")
except ValueError as error:
print(error)The first message says a bytes-like object is required, not str. The second says binary mode doesn't take an encoding argument. To store text in a binary file, encode it yourself with "text".encode("utf-8"). To interpret bytes you read as text, call .decode("utf-8").
Why read in chunks
f.read() with no argument loads the whole file into memory. That is fine for a small configuration file. It is a problem for a 4 GB video, because your process needs 4 GB of free memory just to hold it. Calling read(size) repeatedly lets you process a file in pieces, so memory use depends on the chunk size and not on the file size.
The pattern is a loop that reads a chunk, handles it, and stops when read() returns an empty bytes object. An empty result means end of file.
Copying a file in chunks
This is the standard form of the loop.
with open("input.bin", "rb") as src, open("copy.bin", "wb") as dst:
while chunk := src.read(64 * 1024):
dst.write(chunk)The walrus operator (:=) assigns the result of read() to chunk and tests it in one expression. An empty bytes object is falsy, so the loop ends at end of file. Both files close when the with block ends, even if an exception occurs.
Before Python 3.8 you would write this with while True, an assignment, and an if not chunk: break. Both forms behave the same.
An alternative with iter()
You can express the same loop with the two-argument form of iter(). It calls a function repeatedly until the function returns a sentinel value.
from functools import partial
with open("input.bin", "rb") as src, open("copy.bin", "wb") as dst:
for chunk in iter(partial(src.read, 64 * 1024), b""):
dst.write(chunk)The sentinel must be b"". If you write "" instead, it never equals the bytes that read() returns, and the loop never ends.
Use shutil when you only need a copy
If your goal is simply to copy, the standard library already does this well.
import shutil
shutil.copyfile("input.bin", "copy.bin")shutil.copyfile uses platform-specific fast paths where they exist. Write your own loop when you need to inspect or transform the data on the way through.
Processing a stream: hashing a file
Chunking matters most when you compute something from the data and do not need to keep it. A checksum is a good example, because hash objects accept data incrementally.
import hashlib
def sha256_of(path, chunk_size=1024 * 1024):
digest = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(chunk_size):
digest.update(chunk)
return digest.hexdigest()
print(sha256_of("input.bin"))The result is identical to hashing the whole file at once. Memory use stays near one chunk, whether the file is 1 KB or 100 GB. Since Python 3.11, hashlib.file_digest(f, "sha256") does this loop for you.
Choosing a chunk size
There is no single correct value. These points guide the choice:
- Very small chunks (a few bytes) make the loop run many times, and the Python overhead per iteration dominates.
- Very large chunks use more memory and can hurt cache behavior without making things faster.
- Values from 64 KiB to 1 MiB work well for most disk and network-backed files.
- If speed matters, measure with your real files and storage. Results differ between SSDs, spinning disks, and network drives.
read(n) on a regular buffered file returns exactly n bytes unless it reaches the end of the file, so the last chunk is usually shorter than the others. Do not assume every chunk has the same length. Streams such as sockets or pipes, which Python can also wrap, may return fewer bytes than requested, so always use the length of the data you actually received.
Reusing one buffer with readinto()
Each read() call creates a new bytes object. For most programs that is fine. When you read huge amounts of data and want to avoid repeated allocation, readinto() fills a buffer you provide and returns the number of bytes stored.
buffer = bytearray(64 * 1024)
zero_bytes = 0
with open("input.bin", "rb") as src:
while count := src.readinto(buffer):
zero_bytes += buffer.count(0, 0, count)
print(zero_bytes)Only the first count bytes of the buffer are valid on each pass. The rest hold stale data from the previous iteration, so always limit your processing to count. Here buffer.count(0, 0, count) counts zero bytes in that range only. readinto() returns 0 at end of file, which ends the loop.
Chunks in text mode
You can also pass a size to read() in text mode. There the size counts characters, not bytes. A UTF-8 character can occupy one to four bytes, so a chunk of 1000 characters may span more than 1000 bytes on disk. Python handles the case where a multi-byte character straddles a read boundary, so you never get half a character back.
For text, line iteration (for line in f) is usually better than manual chunking. Chunked text reads are useful when the file has no meaningful line breaks. Binary chunks are the better tool when you care about byte counts, such as when you enforce an upload size limit.
Edge cases and gotchas
- Partial output on failure. If the copy loop fails halfway (disk full, a killed process),
copy.binis left incomplete. For files that other programs read, write to a temporary file and replace it, which a later chapter covers. - Reading and writing the same file. Opening the same path with
wbtruncates it immediately. Never usewbon the file you are still reading from. - Closed files. Using
f.read()after thewithblock ends raisesValueError: I/O operation on closed file. Do all reading inside the block. - Empty files. A zero-byte file makes the first
read()returnb"", so the loop body never runs. Your code should handle that as a normal case. - Position carries over. A file object remembers where it is. If you read a 4-byte header and then start the chunk loop, the loop continues after the header. Moving back to the start needs
seek(), which is the topic of a later chapter.
Summary of the working model
- Add
bto the mode to get raw bytes with no decoding and no newline translation. read()with no argument loads everything.read(n)returns up tonbytes, andb""means end of file.- A
while chunk := f.read(size)loop keeps memory use constant. - Use the length of the data you received, not the chunk size you requested.
- Use
shutil.copyfilefor plain copies andhashlib.file_digestfor hashing when they fit your needs.
Exercise
Write a function count_byte(path, value, chunk_size=65536) that returns how many times the byte with integer value value (0 to 255) appears in the file at path, without loading the whole file into memory. Which mode do you open the file in, and what ends the loop?
Show answer
Open the file in "rb" mode and loop until read() returns an empty bytes object. def countbyte(path, value, chunksize=65536): total = 0 needle = bytes([value]) with open(path, "rb") as f: while chunk := f.read(chunk_size): total += chunk.count(needle) return total bytes.count accepts a bytes argument, so bytes([value]) builds the one-byte pattern. The walrus loop ends when read() returns b"", which is falsy at end of file. Only one chunk is held in memory at a time.
Exercise
A colleague writes for chunk in iter(lambda: f.read(4096), ""): to copy a binary file, and the program never finishes. What is wrong, and how do you fix it?
Show answer
The sentinel is the str "", but a binary file's read() returns bytes. At end of file it returns b"", and b"" == "" is False, so the sentinel never matches and the loop keeps receiving empty chunks forever. Change the sentinel to the bytes literal b"": for chunk in iter(lambda: f.read(4096), b""):