import hashlib
from urllib.request import urlopen
import tempfile
import shutil
url = 'https://example.com/file_name.exe'
with urlopen(url) as f1:
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
shutil.copyfileobj(f1, tmp_file)
with open(tmp_file, 'rb') as f2:
md5 = hashlib.md5()
chunk = 1024
while True:
data = f2.read(chunk)
if not data:
break
md5.update(data)
print(md5.hexdigest())
yanyu-xin
2023-02-24来自广东
import hashlib
from urllib.request import urlretrieve
remote_url = "https://www.python.org/ftp/python/3.10.9/python-3.10.9-amd64.exe"
local_file = "e:\python-3.10.9-amd64.exe"
urlretrieve(remote_url, local_file)
md5 = hashlib.new('md5') #创建md5对象
# 用with同时读取大文件每一行
with open(local_file, "rb") as f:
for fLine in f:
md5.update(fLine.readline())
print(md5.hexdigest()) #返回md5对象
Matthew
2023-01-05来自江苏
import hashlib
from urllib.request import urlretrieve
def get_file_md5(file_name, blobk_size):
"""
计算大文件的md5
"""
m = hashlib.new('md5') #创建md5对象
with open(file_name,'rb') as fobj:
while True:
data = fobj.read(blobk_size)
if not data:
break
m.update(data) #更新md5对象
return m.hexdigest() #返回md5对象
if __name__ == '__main__':
remote_url = "https://www.python.org/ftp/python/3.10.9/python-3.10.9-amd64.exe"
local_file = "./python-3.10.9-amd64.exe"
urlretrieve(remote_url, local_file)
f_md5 = get_file_md5(local_file, 10)
print(f_md5)