用python写一个显示文件下载速度的程序
时间: 2023-03-23 19:03:00 浏览: 149
好的,下面是一个用Python编写的显示文件下载速度的程序:
```python
import requests
import time
def download_file(url, file_name):
# 开始下载文件
start_time = time.time()
response = requests.get(url, stream=True)
# 获取文件大小和类型
total_size = int(response.headers.get('content-length', 0))
file_type = response.headers.get('content-type')
# 打开文件并逐步写入
with open(file_name, 'wb') as f:
chunk_size = 1024
for data in response.iter_content(chunk_size):
f.write(data)
# 计算下载用时和平均下载速度
end_time = time.time()
download_time = end_time - start_time
download_speed = total_size / download_time / 1024 / 1024
# 打印下载信息
print(f"文件类型:{file_type}")
print(f"文件大小:{total_size / 1024 / 1024:.2f} MB")
print(f"下载用时:{download_time:.2f} 秒")
print(f"平均下载速度:{download_speed:.2f} MB/s")
# 调用下载函数
url = 'https://example.com/example.zip'
file_name = 'example.zip'
download_file(url, file_name)
```
以上代码使用Python中的requests库来下载文件,并计算了下载用时和平均下载速度,并在最后输出了下载信息。您可以将代码中的URL和文件名替换为您要下载的文件的URL和文件名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)