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)
较大文件处理方法:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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'