Python有hashlib库,支持多种哈希算法,比如MD5、SHA1、SHA256等。通常SHA256比较安全,但MD5更快,但可能存在碰撞风险,得根据自己需求决定。
下面以SHA256做例。
import hashlib
import os
from typing import Dict, List
def calculate_file_hash(filepath: str, algorithm='sha256') -> str:
"""计算文件的哈希值"""
hasher = hashlib.new(algorithm)
with open(filepath, 'rb') as f:
while chunk := f.read(8192):
hasher.update(chunk)
return hasher.hexdigest()
def build_hash_table(directory: str) -> Dict[str, List[str]]:
"""构建目录文件的哈希映射表"""
hash_table = {}
for root, _, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
try:
file_hash = calculate_file_hash(filepath)
hash_table.setdefault(file_hash, []).append(filepath)
except (IOError, PermissionError):
continue
return hash_table
# 使用示例
if __name__ == "__main__":
target_dir = input("输入要扫描的目录:")
target_hash = input("输入要查找的哈希值:").strip().lower()
print("正在构建哈希表...")
hash_map = build_hash_table(target_dir)
if matches := hash_map.get(target_hash):
print(f"找到 {len(matches)} 个匹配文件:")
for path in matches:
print(f"• {path}")
else:
print("未找到匹配文件")
优化方向可存储程序运行的值,和使用argparse来接受命令行参数,或者直接通过input函数获取目录和哈希值。