Created
April 9, 2025 20:26
-
-
Save kirisakow/61cbdc1cdf9255326e5e86daede26229 to your computer and use it in GitHub Desktop.
Python function that computes checksum of a file using one of hashlib algorithms (default: SHA-256). It combines a "modern" implementation with a pre-Python3.11 compatible alternative.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Union | |
import hashlib | |
import os | |
def get_checksum(path_to_file: str, algorithm: Union[str, callable] = hashlib.sha256) -> str: | |
"""A function that computes checksum of a file using one of hashlib algorithms (default: SHA-256). It combines | |
a "modern" implementation with a pre-Python3.11 compatible alternative.""" | |
if not os.path.exists(path_to_file): | |
raise FileNotFoundError(f"File {path_to_file!r} doesn't seem to exist") | |
if hasattr(hashlib, 'file_digest'): | |
with open(path_to_file, 'rb') as fh: | |
return hashlib.file_digest(fh, algorithm).hexdigest() | |
# Below is a pre-Python3.11 compatible alternative implementation. Source: | |
# https://stackoverflow.com/questions/22058048/hashing-a-file-in-python/44873382#44873382 | |
h = algorithm() | |
b = bytearray(128*1024) | |
mv = memoryview(b) | |
with open(path_to_file, 'rb', buffering=0) as f: | |
for n in iter(lambda: f.readinto(mv), 0): | |
h.update(mv[:n]) | |
return h.hexdigest() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment