[Python] MD5 指定的檔案
阿新 • • 發佈:2018-12-23
範例1:
import sys import hashlib #save as md5_study.py def md5(fileName): """Compute md5 hash of the specified file""" m = hashlib.md5() try: fd = open(fileName,"rb") except IOError: print "Reading file has problem:", filename return x = fd.read() fd.close() m.update(x) return m.hexdigest() if __name__ == "__main__": for eachFile in sys.argv[1:]: print "%s %s" % (md5(eachFile), eachFile)
Note that sometimes you won’t be able to fit the whole file in memory. In that case, you’ll have to read chunks of 4096 bytes sequentially and feed them to the Md5 function:
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096 ), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()