Sub topic 10
Binary files and reading in chunks
This chapter assumes you know how to open a file with open(), use the with statement, and tell str from bytes. Text mode decodes bytes into strings for you. Binary mode skips that step and gives you the raw bytes.
Text mode versus binary mode
Add b to the mode to open a file in binary mode. "rb" reads, "wb" writes (and truncates), and "ab" appends. In binary mode read() returns bytes, and write() accepts only bytes-like objects.
Do not pass encoding= or newline= when you open a file in binary mode. Python raises ValueError if you do, because no decoding takes place.
| Aspect | Text mode (`"r"`) | Binary mode (`"rb"`) |
|---|---|---|
| `read()` returns | `str` | `bytes` |
| Decoding | Uses the `encoding` argument | None |
| Newline translation | Yes | None |
| Typical use | Notes, logs, source code | Images, archives, any file you copy unchanged |
Use binary mode when you do not need to interpret the content, or when the content is not text at all: images, PDFs, ZIP files, or a file you want to copy byte for byte.
with open("input.bin", "wb") as f:
f.write(b"\x89PNG\r\n") # bytes literal
f.write(bytes([0, 255])) # bytes built from integers
with open("input.bin", "rb") as f:
data = f.read()
print(data)
print(data[0]) # indexing bytes gives an int, not a one-byte bytes objectIndexing a bytes object returns an int from 0 to 255. Slicing returns bytes. This difference surprises many people.
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 10 GB video.
A chunked read asks for a fixed number of bytes at a time. Memory use stays near the chunk size no matter how large the file is.
Copying a file in chunks
with open("input.bin", "rb") as src, open("copy.bin", "wb") as dst:
while chunk := src.read(64 * 1024):
dst.write(chunk)Here is how the loop works:
src.read(64 * 1024)returns up to 65,536 bytes.- The walrus operator
:=assigns the result tochunkand tests it in one step. - An empty
bytesobject is falsy, so the loop ends at end of file. - A single
withstatement opens both files, and both are closed even if an error occurs.
read(n) may return fewer than n bytes only at the end of the file, for ordinary disk files. For sockets and pipes, a short read can happen at any time, so always loop until you get an empty result.
If you only need to copy, shutil.copyfileobj(src, dst) does the same loop for you. Writing the loop yourself is useful when you want to process each chunk, for example to hash it.
import hashlib
digest = hashlib.sha256()
with open("copy.bin", "rb") as f:
while chunk := f.read(64 * 1024):
digest.update(chunk)
print(digest.hexdigest())This computes a checksum of a file of any size with constant memory.
Choosing a chunk size
The chunk size trades the number of calls against memory use. Very small chunks (say 16 bytes) make the loop slow because of per-call overhead. Very large chunks use more memory without much speed gain. Values from 8 KiB to 1 MiB work well. 64 KiB is a common default.
Common mistakes
- Mixing
strandbytes.f.write("text")on a file opened with"wb"raisesTypeError. Encode first with"text".encode("utf-8"). - Using
while Truewith a missing break. If you never check for the empty result, the loop runs forever. - Reading a binary file in text mode. Decoding can fail with
UnicodeDecodeError, and newline translation can silently corrupt the data. - Comparing with
"". In binary mode, end of file isb"", not"". Testing truthiness, as the loop above does, avoids this.
Exercise
A script copies a large video with dst.write(src.read()) and runs out of memory. Rewrite the copy so memory use stays constant, and say what ends the loop.
Show answer
Open both files in binary mode and loop: with open("in.mp4", "rb") as src, open("out.mp4", "wb") as dst: then while chunk := src.read(64 * 1024): dst.write(chunk). The loop ends when read() returns an empty bytes object, which is falsy. Memory use stays near 64 KiB because only one chunk is held at a time.
Exercise
What does data[0] return when data = b"AB", and what does data[0:1] return?
Show answer
data[0] returns the integer 65. data[0:1] returns b"A", a bytes object of length one.