Open1
Pythonでファイルハッシュキーの生成
def calculate_file_hash(filepath: Path, hash_algorithm="sha256", chunk_size=8192) -> str:
"""
指定されたファイルのハッシュキーを計算する
Args:
filepath (Path): ハッシュキーを計算するファイルのパス
hash_algorithm(str): 使用するハッシュアルゴリズム
chunk_size(int): ファイルの読み込む際のチャンクサイズ。
Returns:
str: 計算されたハッシュキーの16進数文字列
"""
hasher = hashlib.new(hash_algorithm)
try:
with open(filepath, "rb") as f:
while chunk := f.read(chunk_size):
hasher.update(chunk)
return hasher.hexdigest()
except Exception as e:
logger.warning(f"ハッシュキーの計算に失敗 {filepath}, {e}")
return "Error"