[Python] MD5 指定的檔案

範例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)


範例2:
http://stackoverflow.com/questions/3431825/generating-an-md5-checksum-of-a-file

You can use hashlib.md5()

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()

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *