在Python中下载文件

时间:2010-11-11 06:16:26

标签: python urllib2

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()

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

2 个答案:

答案 0 :(得分:5)

使用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

答案 1 :(得分:1)

显示文件名:print f.name

要查看使用该文件可以执行的所有酷操作:dir(f)

当你说:

时,我不确定我是什么意思
how to display how long it has before the file is finished downloading

如果您想显示下载所需的时间,那么您可能需要查看timeit模块。

我这不是您想要的,请更新问题,以便我可以尝试给您更好的答案

相关问题