使用md5()函数在Python中对文件进行校验和计算的示例代码
发布时间:2023-12-26 03:30:18
示例代码如下所示:
import hashlib
def calculate_md5(file_path):
try:
# Open the file in binary mode
with open(file_path, 'rb') as file:
# Create an instance of the MD5 hash object
md5_hash = hashlib.md5()
# Read the file in chunks and update the hash object
for chunk in iter(lambda: file.read(4096), b''):
md5_hash.update(chunk)
# Get the final MD5 hash value as a hexadecimal string
md5_checksum = md5_hash.hexdigest()
# Return the MD5 hash value
return md5_checksum
except IOError:
print(f"Error: Could not open file '{file_path}'")
return None
# Usage example:
file_path = '/path/to/your/file.ext'
md5_checksum = calculate_md5(file_path)
if md5_checksum:
print(f"MD5 checksum of {file_path}: {md5_checksum}")
使用例子:
# Example 1: Calculate MD5 checksum of a text file
file_path = 'example.txt'
md5_checksum = calculate_md5(file_path)
if md5_checksum:
print(f"MD5 checksum of {file_path}: {md5_checksum}")
# Output: MD5 checksum of example.txt: 098f6bcd4621d373cade4e832627b4f6
# Example 2: Calculate MD5 checksum of an image file
file_path = 'example.jpg'
md5_checksum = calculate_md5(file_path)
if md5_checksum:
print(f"MD5 checksum of {file_path}: {md5_checksum}")
# Output: MD5 checksum of example.jpg: c4ca4238a0b923820dcc509a6f75849b
# Example 3: Calculate MD5 checksum of a non-existing file
file_path = 'non_existing_file.txt'
md5_checksum = calculate_md5(file_path)
# Output: Error: Could not open file 'non_existing_file.txt'
