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基础 range的用法解析

range基本用法: range:顾头不顾尾 range(10)--返回0-9的数字 ey: for i in range(10): print(i) result:0...

python 多进程并行编程 ProcessPoolExecutor的实现

使用 ProcessPoolExecutor from concurrent.futures import ProcessPoolExecutor, as_completed im...

pygame游戏之旅 添加icon和bgm音效的方法

pygame游戏之旅 添加icon和bgm音效的方法

本文为大家分享了pygame游戏之旅的第14篇,供大家参考,具体内容如下 添加icon需要用的函数是: gameIcon = pygame.image.load("carIcon.p...

python简单实现旋转图片的方法

本文实例讲述了python简单实现旋转图片的方法。分享给大家供大家参考。具体实现方法如下: # rotate an image counter-clockwise using the...

Python对列表的操作知识点详解

Python对列表的操作知识点详解

Python的数据结构有列表、元组、集合、字典等,可以吧列表当成一个清单,是有序的,我们可以通过索引访问到列表中的元素,列表还可以进行修改、新增和删除的操作。列表中的数据类型是不限制的,...