python-文件校验
2024-09-05 15:03:02
使用hashlib的md5方法对文件进行加密,目的是为了保证文件在传输的过程中是否发生变化。
#!/usr/bin/python3
# coding:utf-8
# Auther:AlphaPanda
# Description:使用hashlib模块,对文件内容进行校验。以此来判断文件传输过程中是否发生变化,或者有损坏
# Version:1
# Date:Fri Dec 6 22:15:16 EST 2019
import hashlib
# 针对小文件的内容校验
def check_md5(file):
with open(file,mode="rb") as fp:
res = fp.read()
hs = hashlib.md5()
hs.update(res)
return hs.hexdigest() res = check_md5("ceshi1.txt")
print(res) # 针对大文件的内容校验
hs = hashlib.md5()
hs.update("你好\n世界".encode())
print(hs.hexdigest()) hs = hashlib.md5()
hs.update("你好".encode())
hs.update("\n世界".encode())
print(hs.hexdigest())
# 通过以上实验,证明一次加密文件的一行,依次加密完所有的文件内容和一次加密所有的文件内容,所获得的hash值一样。 # 大文件校验方法1:
def check2_md5(file):
hs = hashlib.md5()
with open(file,mode="rb") as fp:
while True:
content = fp.read(3)
if content:
hs.update(content)
else:
break
return hs.hexdigest() print(check2_md5("ceshi3.txt")) # 方法二:
import os
def check4_md5(file):
# 计算文件大小
file_size = os.path.getsize(file)
hs = hashlib.md5()
with open(file,mode="rb") as fp:
while file_size:
# 一次最多读取三个字节
content = fp.read(3)
hs.update(content)
file_size -= len(content)
return hs.hexdigest() print(check4_md5("ceshi4.txt"))
最新文章
- 手动获取spring的ApplicationContext和bean对象
- 【转载】浅谈HTTP中Get与Post的区别
- js的DOM对象
- eclipse + maven 搭建springMVC+Spring+mybatis 系统
- 封装,策略模式,Asp换脸
- HAML学习
- InteractivePNG
- HDU-3854 LOOPS
- 使用XmlReader读取xml文件之二
- Java中的==、equals、hasCode方法
- Android - DrawerLayout
- hotspot虚拟机的调试
- 【JDK1.8】JUC.Lock综述
- hdu-1082 Matrix Chain Multiplication---栈的运用
- 转:rabbitMQ 安装与管理
- js之制作简易红绿灯
- selenium与chrome浏览器及驱动的版本匹配
- 1060D Social Circles(贪心)
- 虚拟主机的IIS连接数和访问流量限制各是什么
- Redis入门指南之一(简介)