python 计算文件的md5值实例
较小文件处理方法:
import hashlib import os def get_md5_01(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 if __name__ == "__main__": file_path = r'D:\test\test.jar' md5_01 = get_md5_01(file_path) print(md5_01)
较大文件处理方法:
import hashlib import os def get_md5_02(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 if __name__ == "__main__": file_path = r'D:\test\test.jar' md5_02 = get_md5_02(file_path) print(md5_02)
说明:对于同一个文件,两种方法计算得到的md5是一致的。
注:以上代码在Python 3.x版本测试通过。
相关推荐
FlySky 2020-11-02
逍遥友 2020-10-26
taiyangshenniao 2020-10-05
flycony 2020-09-23
jacktangj 2020-09-18
YENCSDN 2020-09-15
lsjweiyi 2020-09-14
digwtx 2020-09-14
拾毅者 2020-09-14
zlxcsdn 2020-09-13
weiiron 2020-08-17
amazingbo 2020-08-16
郗瑞强 2020-08-16
lispython 2020-08-16
fengling 2020-08-15
xiesheng 2020-08-02
葫芦小金刚 2020-07-28
StevenSun空间 2020-07-26