要比较本地和远程文件的Python代码的MD5哈希值,可以使用以下解决方法:
hashlib
模块,它提供了计算哈希值的功能;导入requests
模块,用于获取远程文件。import hashlib
import requests
def calculate_md5(file_path):
with open(file_path, 'rb') as file:
md5_hash = hashlib.md5()
while chunk := file.read(4096):
md5_hash.update(chunk)
return md5_hash.hexdigest()
local_file_path = 'path/to/local/file.txt'
local_md5 = calculate_md5(local_file_path)
print(f'Local MD5: {local_md5}')
requests
模块发送GET请求,获取远程文件,并计算其MD5哈希值。remote_file_url = 'http://example.com/remote_file.txt'
response = requests.get(remote_file_url)
remote_md5 = hashlib.md5(response.content).hexdigest()
print(f'Remote MD5: {remote_md5}')
if local_md5 == remote_md5:
print('Files are identical.')
else:
print('Files are different.')
完整示例代码如下:
import hashlib
import requests
def calculate_md5(file_path):
with open(file_path, 'rb') as file:
md5_hash = hashlib.md5()
while chunk := file.read(4096):
md5_hash.update(chunk)
return md5_hash.hexdigest()
local_file_path = 'path/to/local/file.txt'
local_md5 = calculate_md5(local_file_path)
print(f'Local MD5: {local_md5}')
remote_file_url = 'http://example.com/remote_file.txt'
response = requests.get(remote_file_url)
remote_md5 = hashlib.md5(response.content).hexdigest()
print(f'Remote MD5: {remote_md5}')
if local_md5 == remote_md5:
print('Files are identical.')
else:
print('Files are different.')
下一篇:比较本地列表和数据库