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.
Python code
18 linesimport 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
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
- Use `hashlib.file_digest(file, 'sha256')` available in Python 3.11+
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.