在Python中获取文件哈希值通常使用 `hashlib` 模块,该模块提供了多种常见的哈希算法,如MD5、SHA1、SHA256等。以下是获取文件哈希值的步骤和示例代码:
准备工作:
定义文件路径。
file_path = "example.txt" 替换为实际文件路径
读取文件:
使用 `open` 函数以二进制模式读取文件内容。
with open(file_path, "rb") as file:file_content = file.read()
计算哈希值:
使用 `hashlib` 中的相应函数计算哈希值。
import hashlib选择哈希算法,例如MD5hash_object = hashlib.md5(file_content)file_hash = hash_object.hexdigest()
输出结果:
打印或返回文件内容的哈希值。

print(file_hash)
对于大文件,可以使用 `itertools.islice` 函数和分块读取的方式来计算哈希值,以避免一次性将整个文件加载到内存中。
import hashlibfrom itertools import islicedef md5_for_large_file(file_path, chunk_size=1024*1024):md5 = hashlib.md5()with open(file_path, "rb") as f:while True:data = f.read(chunk_size)if not data:breakmd5.update(data)return md5.digest()
另外,从Python 3.8开始,可以使用更简洁的方法来计算文件的哈希值:
import osimport hashlibdef file_hash(file_path: str, hash_method) -> str:if not os.path.isfile(file_path):print('文件不存在。')return ''h = hash_method()with open(file_path, "rb") as f:while True:b = f.read(8192)if not b:breakh.update(b)return h.hexdigest()
使用这个函数,你可以方便地计算文件的哈希值。
