← all snippets

hash-file

Prints the SHA-256 checksum of a file. Use it to verify a download, compare two files for equality, or fingerprint a build artifact.

Python 3 #01

Source

hash-file.py
#!/usr/bin/env python3
"""Print the SHA-256 checksum of a file."""
import hashlib
import sys


def hash_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: hash-file.py <path>")
    try:
        print(hash_file(sys.argv[1]))
    except OSError as e:
        sys.exit(f"error: {e}")

Input

pathstring — positional argument, path to a local file to hash, e.g. build/app.tar.gz

Output

Prints the 64-character lowercase hex SHA-256 digest to stdout, then exits 0. Exits with a non-zero status and an error: ... message on stderr if the file can't be read.

Usage

$ python3 hash-file.py build/app.tar.gz
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

Config

No configuration required.

Security notes

  • File is read in 64 KB chunks, not loaded whole into memory, so it's safe on very large files.
  • Uses SHA-256 (not MD5/SHA-1) for a collision-resistant fingerprint.
  • No shell invocation, no dynamic code execution — plain file I/O only.