在下载大文件时,实时显示下载进度可以帮助我们更好地了解下载情况,避免长时间等待的烦恼。Python 中有多种方法可以实现文件下载进度的实时显示。以下是一些简单而有效的方法:
使用
requests
库
requests
是 Python 中一个常用的 HTTP 库,它提供了非常方便的 API 来进行网络请求。以下是如何使用
requests
库实现文件下载进度显示的示例:
import requests
from tqdm import tqdm
def download_file(url, filename):
with requests.get(url, stream=True) as r:
r.raise_for_status()
total_length = int(r.headers.get(‘content-length’))
with open(filename, ‘wb’) as f:
for data in tqdm(r.iter_content(chunk_size=4096), total=total_length//4096, unit=’KB’):
f.write(data)
# 使用示例
download_file(‘https://example.com/largefile.zip’, ‘largefile.zip’)
在这个例子中,
tqdm
是一个快速、可扩展的进度条库,它可以与任何可迭代对象一起使用,显示进度信息。
使用
urllib
库
如果你不想安装额外的库,可以使用 Python 的标准库
urllib
来实现下载,并结合
sys
和
os
库来显示进度:
import urllib.request
import sys
import os
def download_file(url, filename):
with urllib.request.urlopen(url) as response, open(filename, ‘wb’) as out_file:
file_size = int(response.info()[‘Content-Length’])
downloaded = 0
block_size = 4096
while True:
buffer = response.read(block_size)
if not buffer:
break
downloaded += len(buffer)
print(f”\r{downloaded * 100 // file_size}% downloaded”, end=”)
sys.stdout.flush()
print()
# 使用示例
download_file(‘https://example.com/largefile.zip’, ‘largefile.zip’)
在这个例子中,我们通过读取文件的块来更新下载进度,并使用
\r
来返回行首,从而覆盖之前的输出。
使用
aiohttp
库(异步下载)
如果你需要处理多个下载任务或者希望下载过程更加高效,可以使用
aiohttp
库实现异步下载,并显示进度:
import aiohttp
import asyncio
from tqdm import tqdm
async def download_file(session, url, filename):
async with session.get(url) as response:
total_length = int(response.headers.get(‘content-length’, 0))
with open(filename, ‘wb’) as f:
async for data in tqdm(response.content.iter_chunked(1024), total=total_length//1024, unit=’KB’):
f.write(data)
async def main():
url = ‘https://example.com/largefile.zip’
filename = ‘largefile.zip’
async with aiohttp.ClientSession() as session:
await download_file(session, url, filename)
# 运行异步下载
asyncio.run(main())
在这个例子中,我们使用了
aiohttp
来异步地获取数据,并使用
tqdm
来显示进度。
通过上述方法,你可以轻松地在 Python 中实现文件下载进度的实时显示,从而告别等待的烦恼。选择合适的方法取决于你的具体需求和偏好。