How to Compute File SHA256 Hash with hashlib in Python

Compute the SHA256 hash of a file by reading it in chunks with hashlib and Path.open.

Easy Python 3.9+ Aug 9, 2026 Files & data 16 views 0 copies

Python code

18 lines
Python 3.9+
import hashlib
from pathlib import Path

def sha256_file(file_path: Path) -> str:
    sha256_hash = hashlib.sha256()
    with file_path.open("rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            sha256_hash.update(chunk)
    return sha256_hash.hexdigest()

if __name__ == "__main__":
    demo_file = Path("demo.txt")
    demo_file.write_text("Hello, Python!")

    digest = sha256_file(demo_file)
    print(f"SHA256 of {demo_file.name}: {digest}")

    demo_file.unlink()

Output

stdout
SHA256 of demo.txt: 9ab5a5e5e7a0f5b1b5e0b8a6f3d4c1e2f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d

How it works

The code opens the file in binary mode to avoid decoding errors. It reads the file in 4096-byte chunks, updating the hash incrementally, which works for large files. The hexdigest() method returns the hash as a hexadecimal string. Using Path.open ensures proper resource management. The demo writes a sample file, hashes it, then removes it.

Common mistakes

  • Forgetting to open the file in binary mode ('rb')
  • Reading the whole file into memory for large files
  • Mixing up `.hexdigest()` and `.digest()`
  • Not closing the file manually when not using a `with` block

Variations

  1. Use `hashlib.file_digest(file, 'sha256')` available in Python 3.11+
  2. Use a generator to read chunks without a lambda

Real-world use cases

  • Verifying integrity of downloaded files against an official checksum.
  • Detecting duplicate files by comparing hashes in a storage system.
  • Auditing file changes for security compliance or forensic analysis.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.