python urllib2 下载大小

标签 python download urllib2 filesize

我想用 urllib2 下载一个文件,同时我想显示一个进度条.. 但是我怎样才能得到实际下载的文件大小呢?

我现在的代码是

ul = urllib2.urlopen('www.file.com/blafoo.iso')
data = ul.get_data()

open('file.iso', 'w').write(ul.read())

如果从网站接收到整个下载,数据首先写入文件。 我如何访问下载的数据大小?

谢谢你的帮助

最佳答案

这是一个使用很棒的 requests 的文本进度条示例图书馆和 progressbar图书馆:

import requests
import progressbar

ISO = "http://www.ubuntu.com/start-download?distro=desktop&bits=32&release=lts"
CHUNK_SIZE = 1024 * 1024 # 1MB

r = requests.get(ISO)
total_size = int(r.headers['content-length'])
pbar = progressbar.ProgressBar(maxval=total_size).start()

file_contents = ""
for chunk in r.iter_content(chunk_size=CHUNK_SIZE):
    file_contents += chunk
    pbar.update(len(file_contents))

这是我在运行时在控制台中看到的:

$ python requests_progress.py
 90% |############################   |

编辑:一些注释:

  • 并非所有服务器都提供内容长度 header ,因此在这种情况下,您无法提供百分比
  • 如果文件很大,您可能不想读取内存中的整个文件。您可以将 block 写入文件或其他位置。

关于python urllib2 下载大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11830586/

相关文章:

python - Nose 不从导入的模块运行 doctests

php - 在我的插件中创建 WordPress 页面以将 MySQL 数据导出为 CSV

android - 使用代码从 PDF 中提取文本

python - 尝试在 python 中发布多部分表单数据,不会发布

python - 如何从 urlib2 请求中获取完整的 header 信息?

python - 使用 urllib2 将 solr curl updateJSON 语法转换为 python

python - 如何从 Python 中的两个 n 维数组中获取匹配的行?

python - 如何修复 Tkinter?每个带有 GUI 的代码都会通过 respring 使 mac os 崩溃

python - 值错误 : Found arrays with inconsistent numbers of samples

android - AsyncTask<> 永远不会在 onCreate() 中调用以从 Web 下载图像