计算两个文件的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)
这个脚本包含两个主要功能:
calculate_md5(file_path)
: 计算指定文件的MD5值。compare_and_transfer(source_file, destination_file)
: 比较源文件和目标文件的MD5值,如果不一致则重新传输文件。
你可以根据需要调整文件路径并运行这个脚本来实现文件传输前后的MD5值比较和文件重新传输的功能。