Python 3.11+hashlibfunction
hashlib.file_digest()
hashing
A file's hash in one call: it reads a file opened in binary mode chunk by chunk and returns a ready hash object.
Syntax
hashlib.file_digest(fileobj, digest, /)
It replaces the manual loop of f.read(65536) and update(), and memory use does not depend on the file size. A file opened in text mode is rejected with ValueError — you need 'rb'. It returns an object, not a string: call hexdigest() next. Closing the file is the caller's job, so put the call inside with.
Examples
import hashlib
with open('data.bin', 'wb') as f:
f.write(b'hello world')
with open('data.bin', 'rb') as f:
digest = hashlib.file_digest(f, 'sha256')
print(digest.hexdigest()[:16]) # → b94d27b9934d3e08
import hashlib
with open('data.txt', 'w') as f:
f.write('hello world')
with open('data.txt') as f:
try:
hashlib.file_digest(f, 'sha256')
except ValueError:
print('нужен режим rb') # → нужен режим rb
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy