For the correct and efficient computation of the hash value of a file (in Python 3):
'b'
to the filemode) to avoid character encoding and line-ending conversion issues.readinto()
to avoid buffer churning.Example:
import hashlib
def sha256sum(filename):
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()