brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's hashlib.file_digest checksums a file without a read loop

Python
~/tips/tip-python-hashlib-file-digest

import hashlib

Compute a SHA256 checksum of a file in one call, even for big files.

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

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link