Skip to content

Instantly share code, notes, and snippets.

@rileymjohnson
Created March 22, 2023 19:52
Show Gist options
  • Save rileymjohnson/06b88fa79608befa4872a41fa5bdde86 to your computer and use it in GitHub Desktop.
Save rileymjohnson/06b88fa79608befa4872a41fa5bdde86 to your computer and use it in GitHub Desktop.
Hash a file in Python using sha256 and memoryview
from path import Pathlib
import hashlib
def hash_file(file: str | Path) -> str:
sha256 = hashlib.sha256()
file_mem_view = memoryview(
bytearray(128 * 1024)
)
with open(file, 'rb', buffering=0) as f:
while n := f.readinto(file_mem_view):
sha256.update(file_mem_view[:n])
return sha256.hexdigest()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment