Created
March 22, 2023 19:52
-
-
Save rileymjohnson/06b88fa79608befa4872a41fa5bdde86 to your computer and use it in GitHub Desktop.
Hash a file in Python using sha256 and memoryview
This file contains 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 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