Lesson · File I/O & Filesystem
Working With Binary Files
55 min readWorking With Binary Files
Binary files expose bytes exactly as stored. Chunked I/O, binary formats, archives, and compression all build on the same distinction between byte sequences and decoded text.
Learning goals
- Read and write raw bytes with
"rb"and"wb"modes, and explain why no decoding happens there. - Tell a
bytesobject apart from a one-element slice, and explain whenbytearrayis the right buffer. - Drive a chunked read loop with
file.read(n)and say what the final iteration returns. - Name the tools for compressed streams and for archive containers, including
compression.zstdin Python 3.14. - Predict which write calls accept text and which demand bytes, and read the resulting
TypeError.
Mental model
Binary data keeps its meaning only if the layer that produced it gets it back unchanged, so the stream hands your code bytes slices and never decodes them. A chunk size is a throughput and latency choice, while correctness comes from handling boundaries: the last chunk, the end-of-file signal, and which format-aware tool consumes what you read.
Mental model
read it top to bottom
bytes on storage ↔ binary stream ↔ chunks/buffers ↔ parser/compressor
Version note
Python 3.14 adds the compression package and compression.zstd. Earlier versions use the older standalone compression modules.
Core idea
Binary mode makes the smallest possible promise: the stream moves bytes, undecoded and untranslated. Everything else in the lesson, chunked reads, compression streams, archive containers, is built by slicing or wrapping those same bytes, so the design questions become where one chunk ends, how much data must be in memory at once, and whether the bytes came from a source you trust.
Bytes
Bytes are immutable sequences of small integers (0 to 255), produced by bytes(...), b"..." literals, or any binary read. Indexing returns an int, slicing returns bytes, and there is no character decoding anywhere in the type; use bytearray when the same buffer must be modified in place.
Binary mode
Binary mode reads and writes bytes without text encoding or newline translation. Use it for images, compressed data, executable formats, and protocols defined in bytes.
Chunked reads
Chunked reading limits memory use by processing a fixed amount of binary data at a time. Choose chunk size based on throughput needs rather than correctness alone.
Binary writes
A binary write sends bytes (or a buffer such as bytearray) to the stream with write(), which returns the number of bytes written, and raises TypeError if given a str. No newline translation or encoding happens, and the position advances by exactly the byte count, which is what lets code write headers and payloads to precise offsets.
Archive and compression overview
The standard library splits these tools into compressors that wrap a single byte stream (gzip, bz2, lzma, and 3.14's compression.zstd) and container formats that bundle many named files (zipfile, tarfile, usually combined with one of the compressors). Choosing starts with one question: is this one stream or many named members? Size, speed, and compatibility with other tools decide the codec after that.
compression package and compression.zstd (Python 3.14)
Python 3.14 adds the compression package and standard-library Zstandard support through compression.zstd. Use compression APIs when storage or transfer size matters, but account for CPU cost and streaming needs.
gzip, bz2, lzma, zipfile, and tarfile overview
gzip, bz2, and lzma work with compressed streams, while zipfile and tarfile work with archive containers. Archives can contain paths, so extraction requires the same security care as other untrusted filesystem input.
Python 3.14 example: Zstandard
For large streams, prefer streaming compressor/decompressor APIs instead of one-shot functions that require the full payload in memory.
from compression import zstd payload = b"Python " * 100 compressed = zstd.compress(payload) restored = zstd.decompress(compressed) assert restored == payload print(len(payload), len(compressed))
Common mistakes
- Opening a binary file without
"b"and reading it as text: the decode step hits a byte the encoding cannot map and raisesUnicodeDecodeErroreven though the bytes themselves are intact. - Assuming
read(n)always returnsnbytes: it returns fewer near the end andb""after it, so a loop that trusts a fixed size can corrupt the last block or never terminate. - Comparing an indexed byte with a one-byte object:
chunk[0] == b"\x00"is alwaysFalsebecause indexing yields anint, whilechunk[:1] == b"\x00"compares twobytesvalues. - Extracting archives without checking what is inside: member names and sizes come from the archive, so a path can escape the destination and a large member can fill the disk; Python's extraction filters exist for exactly this reason.
Practice: Easy
- Write
bytes(range(16))todata.binwithwrite_bytes, then read it back twice, once with aread(4)loop and once withread(), and confirm both produce the same 16 bytes. - Print
data[:4],data[0], andlen(data)for the 16-byte object and label each result with its type. - Read the first 8 bytes of an image file you have around and compare them with that format's known signature.
Practice: Medium
- Rewrite the chunk loop to accumulate into a
bytearrayand assert the result equalsbytes(range(16)); explain whybytearrayfits an in-progress copy. - Copy a file in 64 KB chunks; test on a file of at least 10 MB and compare the result with the original by hash or equality.
- Compress the same payload with
zstd.compressand withgzip.compressand compare the lengths; explain why a small payload may not show the expected ordering of the two formats.
Practice: Hard
- Build
copy(source, target, chunk=65536)that never loads the whole file, verify it on a multi-megabyte binary, and define its behavior when the target exists. - Design a reader for a small binary record format (4-byte length, then that many payload bytes) using
int.from_bytesandto_bytes; test it with a truncated file and confirm the EOF handling. - Decompress a gzip file in chunks with
gzip.open(path, "rb"), never holding the full payload; describe where decompressed data is buffered and why this is the streaming path.
Lesson checklist
- I can explain why binary mode never decodes bytes or translates newlines.
- I can write a chunked read loop and say what ends it.
- I can tell indexing a
bytesobject apart from slicing it. - I can choose between the compression modules and the archive modules for a given task.
Remember
Binary mode moves bytes with no interpretation, which is the only correct mode for images, compressed data, archives, and any format whose meaning lives at the byte level. Chunked reads bound memory at the cost of handling a short final chunk, and the compression and archive tools in this lesson are wrappers around the same byte flow: compressors wrap one stream, archives bundle many named files, and archive contents stay untrusted input regardless of the library.
Interview angles
What is the main purpose of **Bytes**?+
Bytes are immutable sequences of integers from 0 to 255, produced by literals such as b"...", by bytes(...), or by any binary read. Indexing yields an int, slicing yields bytes, and no character decoding occurs anywhere in the type; bytearray is the mutable counterpart when a buffer must change in place.
What should you pay attention to when using **Binary mode**?+
Binary mode reads and writes bytes without text encoding or newline translation. Use it for images, compressed data, executable formats, and protocols defined in bytes.
How does **Chunked reads** fit into this lesson?+
Chunked reading limits memory use by processing a fixed amount of binary data at a time. Choose chunk size based on throughput needs rather than correctness alone.
Why can a chunked copy loop that trusts `read(n)` to return `n` bytes produce a wrong result?+
read(n) may return fewer bytes on the final read and b"" once the stream is exhausted; a loop that assumes a full block can pad, truncate, or never stop. Treat a short read as data and an empty result as the terminator.