python 20 lines · 6 steps

Streaming SHA-256 checksums in Python

Hash a file in fixed-size chunks so you never load the whole thing into memory, then verify it against an expected value.

Explained by highlit
1import hashlib
2from pathlib import Path
3 
4 
5def sha256_checksum(path, chunk_size=65536):
6 digest = hashlib.sha256()
7 with open(path, "rb") as f:
8 for chunk in iter(lambda: f.read(chunk_size), b""):
9 digest.update(chunk)
10 return digest.hexdigest()
11 
12 
13def verify_checksum(path, expected):
14 actual = sha256_checksum(path)
15 if actual != expected.lower():
16 raise ValueError(
17 f"checksum mismatch for {Path(path).name}: "
18 f"expected {expected}, got {actual}"
19 )
20 return True
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Reading a file in chunks keeps memory flat regardless of file size.
  2. 2The two-argument form of iter() turns a repeated read into a clean sentinel-terminated loop.
  3. 3Normalizing case before comparing hex digests avoids spurious mismatches.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Streaming SHA-256 checksums in Python — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code