??? Python有hashlib庫,支持多種哈希算法,比如MD5、SHA1、SHA256等。通常SHA256比較安全,但MD5更快,但可能存在碰撞風險,得根據自己需求決定。
? ? ? ? 下面以SHA256做例。
import hashlib
import os
from typing import Dict, Listdef 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):continuereturn 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函數獲取目錄和哈希值。