Checking a download against its published SHA256 used to mean writing a little loop that reads the file in chunks. Since Python 3.11 that loop is built in.
import hashlib
with open("debian.iso", "rb") as f:
digest = hashlib.file_digest(f, "sha256").hexdigest()
expected = "paste the checksum from the download page here"
print("OK" if digest == expected.lower() else "MISMATCH")
file_digest reads the file in blocks behind the scenes, so a 4 GB image doesn’t end up in memory all at once. The result is a normal hash object; hexdigest() gives the string you compare with the website or a SHA256SUMS file.
The file has to be opened in binary mode with "rb". In text mode you get an error instead of a wrong hash, which is the friendlier of the two outcomes.
I like this for scripts that check backups or deduplicate photos, where you’d otherwise copy the same read loop from project to project.
It needs Python 3.11 or newer. On older systems the chunked loop with hashlib.sha256() and update() is still the way. And from the shell, sha256sum on Linux or shasum -a 256 on macOS is quicker if you only need to check one file by hand.
Further reading: hashlib.file_digest