在 Python 中下载文件 [英] Downloading a file in Python

查看:53
本文介绍了在 Python 中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import urllib2, sys如果 len(sys.argv) !=3:打印用法:download.py  "sys.exit(1)站点 = urllib2.urlopen(sys.argv[1])元 = site.info()打印大小:",meta.getheaders(内容长度")f = open(sys.argv[2],'wb')f.write(site.read())f.close()

我想知道如何在下载前显示文件名和大小以及如何显示文件的下载进度.任何帮助将不胜感激.

解决方案

使用 urllib.urlretrieve

<前><代码>导入 urllib, sysdef progress_callback(blocks, block_size, total_size):#blocks-> 到目前为止下载的数据(回调的第一个参数)#block_size -> 每个块的大小#total-size -> 文件大小#实现代码来计算下载的百分比,例如打印下载的 %f%%"% 块/浮点数(total_size)如果 len(sys.argv) !=3:打印用法:download.py"sys.exit(1)站点 = urllib.urlopen(sys.argv[1])(文件,标题)= urllib.urlretrieve(站点,sys.argv[2],progress_callback)打印标题

import urllib2, sys

if len(sys.argv) !=3:
              print "Usage: download.py <link> <saveas>"
              sys.exit(1)

site = urllib2.urlopen(sys.argv[1])
meta = site.info()
print "Size: ", meta.getheaders("Content-Length")
f = open(sys.argv[2], 'wb')
f.write(site.read())
f.close()

I'm wondering how to display the file name and size before downloading and how to display the download progress of the file. Any help will be appreciated.

解决方案

using urllib.urlretrieve


    import urllib, sys

    def progress_callback(blocks, block_size, total_size):
        #blocks->data downloaded so far (first argument of your callback)
        #block_size -> size of each block
        #total-size -> size of the file
        #implement code to calculate the percentage downloaded e.g
        print "downloaded %f%%" % blocks/float(total_size)

    if len(sys.argv) !=3:
        print "Usage: download.py  "
        sys.exit(1)

    site = urllib.urlopen(sys.argv[1])
    (file, headers) = urllib.urlretrieve(site, sys.argv[2], progress_callback)
    print headers

这篇关于在 Python 中下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆