将文件拆分为8192字节的块(或128字节的其他倍数),然后使用连续将其送入MD5
update()。
这利用了MD5具有128字节摘要块(8192为128×64)这一事实。由于您没有将整个文件读入内存,因此占用的内存不会超过8192字节。
在Python 3.8+中,您可以执行
import hashlibwith open("your_filename.txt", "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


