计算两个文件的MD5值是否一致?

计算两个文件的MD5值是否一致?

当然可以,下面是一个Python脚本,用于计算文件的MD5值:

import hashlib

def calculate_md5(file_path):
    """
    计算文件的MD5值

    :param file_path: 文件路径
    :return: 文件的MD5值
    """
    hash_md5 = hashlib.md5()
    try:
        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                hash_md5.update(chunk)
        return hash_md5.hexdigest()
    except FileNotFoundError:
        return None

def compare_and_transfer(source_file, destination_file):
    """
    比较文件的MD5值,如果不同则重新传输文件

    :param source_file: 源文件路径
    :param destination_file: 目标文件路径
    """
    source_md5 = calculate_md5(source_file)
    destination_md5 = calculate_md5(destination_file)

    if source_md5 is None:
        print(f"源文件 {source_file} 未找到。")
        return

    if destination_md5 is None:
        print(f"目标文件 {destination_file} 未找到,将进行传输。")
    elif source_md5 != destination_md5:
        print(f"文件MD5值不一致,重新传输文件。")
    else:
        print(f"文件MD5值一致,无需传输。")
        return

    try:
        with open(source_file, 'rb') as src, open(destination_file, 'wb') as dst:
            dst.write(src.read())
        print(f"文件传输成功。")
    except Exception as e:
        print(f"文件传输失败:{e}")

# 示例使用
source_file_path = 'path/to/source/file'
destination_file_path = 'path/to/destination/file'

compare_and_transfer(source_file_path, destination_file_path)

这个脚本包含两个主要功能:

  1. calculate_md5(file_path): 计算指定文件的MD5值。
  2. compare_and_transfer(source_file, destination_file): 比较源文件和目标文件的MD5值,如果不一致则重新传输文件。

你可以根据需要调整文件路径并运行这个脚本来实现文件传输前后的MD5值比较和文件重新传输的功能。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值