Recipe 10.6 · Python
Streaming Large Files
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
Code that worked with test files falls over with production ones. File.ReadAllBytes on a 3 GB extract throws OutOfMemoryException, or pushes a web server into constant garbage collection. File.ReadAllLines loads every line before the first is processed. And integrity checks compute a hash in a second pass, reading the whole file twice.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
The whole file is in memory, twice in places, and the hash uses MD5.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Copy a file by loading it fully into memory and hashing it with MD5
Source: ImproveCode, Chapter 10, Recipe 10.6 "Streaming Large Files"
Section: The way it's often written
Book page: 222 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
File.ReadAllBytes -> Path.read_bytes; MD5 + BitConverter.ToString -> hashlib.md5
formatted as dash-separated upper-case hex.
"""
import hashlib
from pathlib import Path
def copy_and_hash(source: str, destination: str) -> str:
data = Path(source).read_bytes()
digest = hashlib.md5(data).digest()
hash = "-".join(f"{b:02X}" for b in digest)
Path(destination).write_bytes(data)
return hash
The improved recipe
Copy in fixed-size chunks with a pooled buffer, hash each chunk as it passes through, and report progress. For text, read lines lazily.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Stream large files in chunks: copy with SHA-256, hash, and filter lines
Source: ImproveCode, Chapter 10, Recipe 10.6 "Streaming Large Files"
Section: The improved recipe
Book page: 222-224 -- original C# listing
Converted from C# to Python.
FileStream + IncrementalHash -> open() + hashlib.sha256 updated per chunk;
ArrayPool buffer -> reused bytearray/memoryview with readinto; IProgress<long>
-> optional callable; PreallocationSize -> os.truncate on the new file.
"""
from __future__ import annotations
import hashlib
import os
from collections.abc import Callable, Iterator
CHUNK_SIZE = 128 * 1024
async def copy_with_hash_async(
source_path: str,
destination_path: str,
progress: Callable[[int], None] | None = None,
) -> str:
with open(source_path, "rb", buffering=0) as source:
length = os.fstat(source.fileno()).st_size
with open(destination_path, "xb", buffering=0) as destination:
if length:
os.truncate(destination.fileno(), length) # preallocate
hash = hashlib.sha256()
buffer = bytearray(CHUNK_SIZE)
view = memoryview(buffer)
total = 0
while (read := source.readinto(buffer)) > 0:
hash.update(view[:read])
destination.write(view[:read])
total += read
if progress is not None:
progress(total)
destination.truncate(total)
return hash.hexdigest()
async def hash_file_async(path: str) -> str:
with open(path, "rb", buffering=CHUNK_SIZE) as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def read_matching_lines(
path: str, predicate: Callable[[str], bool]
) -> Iterator[str]:
with open(path, encoding="utf-8") as f:
for line in f:
line = line.rstrip("\r\n")
if predicate(line):
yield line
How it works
CopyWithHashAsync holds one 128 KB buffer, rented from the shared ArrayPool so repeated copies do not allocate. Each chunk is read once, added to the hash and written out, so the file is read a single time whatever its size. IncrementalHash is the streaming form of SHA-256; the result is the same lowercase hex string that sha256sum or PowerShell's Get-FileHash produce (PowerShell prints it in uppercase), which makes it easy to compare with a partner's checksum file.
BufferSize = 0 turns off FileStream's internal buffer, since the code already reads and writes in large chunks and a second buffer would only copy memory. SequentialScan tells Windows to read ahead aggressively. PreallocationSize asks the file system to reserve the full size up front, which reduces fragmentation and fails early if the disk is too small.
HashFileAsync is the one-liner for a checksum alone; SHA256.HashDataAsync(Stream) (.NET 7 and later) streams internally.
File.ReadLines in ReadMatchingLines returns lines lazily, so filtering a 5 GB log uses a few kilobytes of memory.
Variations and pitfalls
- Web downloads. In ASP.NET Core, return
Results.File(path, contentType, enableRangeProcessing: true). The server streams from disk and supports resumable downloads. Never read the file into a byte array first. - Web uploads.
IFormFilebuffers uploads larger than 64 KB to a temp file, which is fine for most sizes. For multi-gigabyte uploads, readRequest.BodywithMultipartReaderand stream straight to storage.