Python实现通过文件路径获取文件hash值的方法
作者:SunboyL 时间:2023-10-27 21:41:20
本文实例讲述了Python实现通过文件路径获取文件hash值的方法。分享给大家供大家参考,具体如下:
import hashlib
import os,sys
def CalcSha1(filepath):
with open(filepath,'rb') as f:
sha1obj = hashlib.sha1()
sha1obj.update(f.read())
hash = sha1obj.hexdigest()
print(hash)
return hash
def CalcMD5(filepath):
with open(filepath,'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
print(hash)
return hash
if __name__ == "__main__":
if len(sys.argv)==2 :
hashfile = sys.argv[1]
if not os.path.exists(hashfile):
hashfile = os.path.join(os.path.dirname(__file__),hashfile)
if not os.path.exists(hashfile):
print("cannot found file")
else
CalcMD5(hashfile)
else:
CalcMD5(hashfile)
#raw_input("pause")
else:
print("no filename")
使用Python进行文件Hash计算有两点必须要注意:
1、文件打开方式一定要是二进制方式,既打开文件时使用b模式,否则Hash计算是基于文本的那将得到错误的文件Hash(网上看到有人说遇到Python的Hash计算错误在大多是由于这个原因造成的)。
2、对于MD5
如果需要16位(bytes)的值那么调用对象的digest()
而hexdigest()
默认是32位(bytes),同理Sha1
的digest()
和hexdigest()
分别产生20位(bytes)和40位(bytes)的hash值
PS:这里再为大家提供2款hash相关在线工具供大家参考使用:
在线散列/哈希算法加密工具:
http://tools.jb51.net/password/hash_encrypt
在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
希望本文所述对大家Python程序设计有所帮助。
标签:Python,文件,hash
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何实现优惠打折?
2010-06-03 10:27:00
python中re.findall函数实例用法
2021-03-28 07:51:20
Django模型层实现多表关系创建和多表操作
2022-12-01 09:13:46
python数据类型中的字符串你了解多少
2023-10-07 19:55:19
python 子类调用父类的构造函数实例
2023-05-27 22:33:37
![](https://img.aspxhome.com/file/2023/5/70135_0s.jpg)
mysql 判断是否为子集的方法步骤
2024-01-26 03:53:11
![](https://img.aspxhome.com/file/2023/3/74783_0s.png)
Python PaddleGAN实现调整照片人物年龄
2023-09-28 05:48:14
![](https://img.aspxhome.com/file/2023/2/90612_0s.png)
Python入门教程(四十)Python的NumPy数组创建
2023-11-14 08:36:32
![](https://img.aspxhome.com/file/2023/0/100820_0s.png)
Go/Python/Erlang编程语言对比分析及示例代码
2022-08-15 17:19:12
![](https://img.aspxhome.com/file/2023/9/79649_0s.jpg)
OpenCV清除小面积连通域的实现方法
2023-11-16 03:58:25
![](https://img.aspxhome.com/file/2023/7/107097_0s.png)
在TensorFlow中实现矩阵维度扩展
2021-09-21 17:50:15
python爬取王者荣耀全皮肤的简单实现代码
2021-03-14 16:36:43
![](https://img.aspxhome.com/file/2023/9/79509_0s.png)
python机器学习案例教程——K最近邻算法的实现
2021-12-01 14:36:51
微信小程序仿朋友圈发布动态功能
2024-04-17 10:01:01
![](https://img.aspxhome.com/file/2023/6/136426_0s.png)
js版实现计算器功能
2024-04-23 09:26:42
![](https://img.aspxhome.com/file/2023/7/135527_0s.jpg)
Python 内置函数速查表一览
2021-10-30 07:43:06
Go Map并发冲突预防与解决
2024-02-19 00:25:24
Javascript技术栈中的四种依赖注入小结
2024-04-18 10:54:08
详解python之heapq模块及排序操作
2023-10-14 04:55:20
SpringBoot集成Flyway进行数据库版本迁移管理的步骤
2024-01-13 19:18:53
![](https://img.aspxhome.com/file/2023/0/83030_0s.png)