python 计算文件的md5值实例

yipeiwu_com6年前Python基础

较小文件处理方法:

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版本测试通过。

以上这篇python 计算文件的md5值实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python 16进制与中文相互转换的实现方法

Python中编码问题:u'\xe6\x97\xa0\xe5\x90\x8d' 类型的转为utf-8的解决办法 相信小伙伴们遇到过类似这样的问题,python2中各种头疼的转码,类似u'...

pytorch自定义二值化网络层方式

任务要求: 自定义一个层主要是定义该层的实现函数,只需要重载Function的forward和backward函数即可,如下: import torch from torch.aut...

在Python中使用lambda高效操作列表的教程

介绍 lambda Python用于支持将函数赋值给变量的一个操作符 默认是返回的,所以不用再加return关键字,不然会报错 result = lambda x: x * x re...

分享Python切分字符串的一个不错方法

一同事问:有一字符串“abcdefghijklmn”如何用Python来切分,每四个一段,剩下的算一段。字符段切分,首先会想到split()和 re.split()函数,但仔细想了一下,...

在Python中使用filter去除列表中值为假及空字符串的例子

在 Python中,认为以下值为假: None # None值 False # False值 0 # 数值零不管它是int,float还是complex类型 '',(),[] #...