python计算文件md5值

较小文件处理方法:

import hashlib
import os

def GetSmallFile(file_path):
  md5 = None
  if os.path.isfile(file_path):
    f = open(file_path,'rb')
    md5_obj = hashlib.md5()
    md5_obj.update(f.read())
    hash_code = md5_obj.hexdigest()
    f.close()
    md5 = str(hash_code).lower()
  return md5

md5 = GetSmallFile(file_path)
print(md5)

 

较大文件处理方法:

import hashlib
import os

"""
    获取文件Md5值
    file_path = r'/opt/code/my_code/zk_css/zk_css.cnf'
    md5_02 = GetBigFileMd5Value(file_path)

"""


def GetBigFileMd5Value(file_path):
    f = open(file_path, 'rb')
    md5_obj = hashlib.md5()
    while True:
        d = f.read(8096)
        if not d:
            break
        md5_obj.update(d)
    hash_code = md5_obj.hexdigest()
    f.close()
    md5 = str(hash_code).lower()
    return md5

 

报错、解决方案

TypeError: Unicode-objects must be encoded before hashing
>>> a = "张三李四王五赵六"
>>> md5_obj.update(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing

 

方法:

>>> md5_obj.update(a.encode("utf-8"))
>>> md5_obj.hexdigest()
'deeea258a3f22c6dd9307e4dd2b6c016'

 

 

 

 

 

 

posted @ 2018-01-06 15:33  我当道士那儿些年  阅读(390)  评论(0编辑  收藏  举报