Python 下载文件
实现代码如下:
import urllib.request
# 定义下载地址和保存路径
url = 'http://192.168.1.10:8080/upload/20251016/1461545746120773.bin'
file_name = 'test.bin'
try:
# 使用urlopen打开URL
with urllib.request.urlopen(url) as response:
# 以二进制写入模式创建文件
with open(file_name, 'wb') as f:
# 逐块读取并写入文件,避免内存问题
while True:
chunk = response.read(8192)
if not chunk:
break
f.write(chunk)
print(f'文件已成功下载并保存为 {file_name}')
except Exception as e:
print(f'下载过程中出现错误: {e}')