import os import hashlib from openpyxl import Workbook def hash_file(file_path, algorithm="md5"): if algorithm.lower() == "md5": hasher = hashlib.md5() elif algorithm.lower() == "sha1": hasher = hashlib.sha1() else: raise ValueError("Invalid hashing algorithm.") with open(file_path, 'rb') as file: buffer = file.read() hasher.update(buffer) return hasher.hexdigest() def hash_directory(directory_path, algorithm="md5"): hashes = {} for dirpath, dirnames, filenames in os.walk(directory_path): for file_name in filenames: file_path = os.path.join(dirpath, file_name) relative_path = os.path.relpath(file_path, directory_path) file_hash = hash_file(file_path, algorithm=algorithm) hashes[relative_path] = {"full_path": file_path, "hash": file_hash} return hashes if __name__ == "__main__": directory_path = "path" # 替换为你的待计算校验值目录文件夹 hashes_md5 = hash_directory(directory_path, algorithm="md5") hashes_sha1 = hash_directory(directory_path, algorithm="sha1") wb = Workbook() ws = wb.active ws.title = "文件哈希值" ws.append(["文件名", "路径", "MD5校验值", "SHA1校验值"]) for rel_path, data in hashes_md5.items(): md5_hash = data["hash"] sha1_hash = hashes_sha1[rel_path]["hash"] # 获取对应的SHA1哈希值 ws.append([rel_path, data["full_path"], md5_hash, sha1_hash]) # 将MD5和SHA1哈希值一起写入工作表 excel_file_path = "path" # 替换为你的csv导出路径 wb.save(excel_file_path) print(f"哈希值已保存至 {excel_file_path}.")
计算目录下所有文件校验值并导出csv表格记录
最新推荐文章于 2024-10-01 23:05:47 发布