In Python 3.8+ you can do
import hashlib
with open("your_filename.png", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
On Python 3.7 and below:
with open("your_filename.png", "rb") as f:
file_hash = hashlib.md5()
chunk = f.read(8192)
while chunk:
file_hash.update(chunk)
chunk = f.read(8192)
print(file_hash.hexdigest())
This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read()
to use less memory.
Consider using hashlib.blake2b
instead of md5
(just replace md5
with blake2b
in the above snippets). It's cryptographically secure and faster than MD5.