有没有什么简单的方法可以在Python中生成(并检查)文件列表的MD5校验和?(我有一个小程序,我正在工作,我想确认文件的校验和)。
当前回答
在Python 3.8+中,你可以像这样使用赋值操作符:=(以及hashlib):
import hashlib
with open("your_filename.txt", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
考虑使用hashlib。Blake2b而不是md5(在上面的代码片段中用Blake2b替换md5)。它是加密安全的,比MD5更快。
其他回答
在Python 3.11+中,有一个新的可读且内存高效的方法:
import hashlib
with open(path, "rb") as f:
digest = hashlib.file_digest(f, "md5")
print(digest.hexdigest())
你可以利用这个壳层。
from subprocess import check_output
#for windows & linux
hash = check_output(args='md5sum imp_file.txt', shell=True).decode().split(' ')[0]
#for mac
hash = check_output(args='md5 imp_file.txt', shell=True).decode().split('=')[1]
你可以使用simple-file-checksum1,它只使用subprocess来调用macOS/Linux的openssl和Windows的CertUtil,并只从输出中提取摘要:
安装:
pip install simple-file-checksum
用法:
>>> from simple_file_checksum import get_checksum
>>> get_checksum("path/to/file.txt")
'9e107d9d372bb6826bd81d3542a419d6'
>>> get_checksum("path/to/file.txt", algorithm="MD5")
'9e107d9d372bb6826bd81d3542a419d6'
支持SHA1、SHA256、SHA384、SHA512四种算法。
披露:我是simple-file-checksum的作者。
将file_path更改为您的文件
import hashlib
def getMd5(file_path):
m = hashlib.md5()
with open(file_path,'rb') as f:
lines = f.read()
m.update(lines)
md5code = m.hexdigest()
return md5code
在Python 3.8+中,你可以像这样使用赋值操作符:=(以及hashlib):
import hashlib
with open("your_filename.txt", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
考虑使用hashlib。Blake2b而不是md5(在上面的代码片段中用Blake2b替换md5)。它是加密安全的,比MD5更快。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录