← Runnable Projects

阅读中文版本

File Checksum Verifier in Python

A Python script that computes a SHA-256 checksum for each file in a directory and compares them against a checksums file to report mismatches.

beginnerpythonunverified

Project

python-md5-checksum

Entry point: checksum.py

Install

python --version

Run

python checksum.py verify checksums.txt

Test

python checksum.py verify checksums.txt

Expected output

Prints OK or FAILED for each file and a summary count of matching and mismatching files.

Dependencies

  • python >=3.10

What it does

Computes streamed SHA-256 checksums and verifies a checksums file, which is the standard way to detect corrupted or altered downloads.

import hashlib
import sys

def checksum(path, chunk=65536):
    digest = hashlib.sha256()
    with open(path, "rb") as handle:
        for block in iter(lambda: handle.read(chunk), b""):
            digest.update(block)
    return digest.hexdigest()

def load_manifest(path):
    entries = {}
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            expected, name = line.split(maxsplit=1)
            entries[name.strip()] = expected.lower()
    return entries

def main():
    command = sys.argv[1]
    if command == "verify":
        entries = load_manifest(sys.argv[2])
        ok = failed = 0
        for name, expected in entries.items():
            try:
                actual = checksum(name)
            except OSError:
                print(f"FAILED {name} (missing)")
                failed += 1
                continue
            status = "OK" if actual == expected else "FAILED"
            print(f"{status} {name}")
            ok += actual == expected
            failed += actual != expected
        print(f"matched={ok} failed={failed}")

if __name__ == "__main__":
    main()

Files are hashed in chunks so a large file does not need to be read into memory at once.

Run and verify

printf 'hello' > file.txt
python checksum.py hash file.txt > checksums.txt
python checksum.py verify checksums.txt

Generate a checksum file from a known file, then verify it; editing the file makes the check fail.

Expected Output

Verifying an untouched file should print OK and a summary of one match. The output is:

OK file.txt
matched=1 failed=0

A modified file prints FAILED with the same name, a missing file is reported as missing, and the summary counts both outcomes.

Limitations

SHA-256 is used rather than MD5 because MD5 is broken for collision resistance; checksums detect corruption but not a maliciously crafted file with a known digest.