在 python 中显示文件下载进度条可以使用 tqdm 库,具体步骤为:1. 安装 tqdm 库;2. 导入 tqdm 库;3. 设置进度条;4. 更新进度条;5. 完成下载。
如何在 Python 中显示文件下载进度条
开门见山:
在 Python 中,可以使用 tqdm 库轻松实现文件下载进度条。
详细解答:
1. 安装 tqdm 库
立即学习“Python免费学习笔记(深入)”;
pip install tqdm
2. 导入 tqdm 库
import tqdm
3. 设置进度条
progress_bar = tqdm.tqdm(total=文件大小)
4. 更新进度条
通过文件流更新:
with open("文件路径", "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
progress_bar.update(len(chunk))
通过下载的文件对象更新:
with tqdm.tqdm(unit="B", unit_scale=True, unit_divisor=1024, total=文件大小) as progress_bar:
while True:
data = 文件对象.read(1024)
if not data:
break
progress_bar.update(len(data))
5. 完成下载
progress_bar.close()
示例:
import tqdm
import requests
# 定义下载 URL
url = "https://example.com/file.zip"
response = requests.get(url, stream=True)
file_size = int(response.headers["Content-Length"])
progress_bar = tqdm.tqdm(total=file_size)
with open("file.zip", "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
progress_bar.update(len(chunk))