计算目录下所有文件校验值并导出csv表格记录

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}.")
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值