較小文件處理方法:
import hashlibimport osdef 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 md5if __name__ == "__main__": file_path = r'D:/test/test.jar' md5_01 = get_md5_01(file_path) print(md5_01)
較大文件處理方法:
import hashlibimport osdef 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 md5if __name__ == "__main__": file_path = r'D:/test/test.jar' md5_02 = get_md5_02(file_path) print(md5_02)
說(shuō)明:對(duì)于同一個(gè)文件,兩種方法計(jì)算得到的md5是一致的。
注:以上代碼在Python 3.x版本測(cè)試通過(guò)。
以上這篇python 計(jì)算文件的md5值實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選