在Python中下载文件

2 投票
2 回答
1867 浏览
提问于 2025-04-16 06:53
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 个回答

1

要显示文件名,可以用这个命令:print f.name

如果想看看你可以对这个文件做哪些有趣的操作,可以用这个命令:dir(f)

我不太明白你说的意思:

how to display how long it has before the file is finished downloading

如果你想显示下载花了多长时间,那你可以看看timeit这个模块。

如果这不是你想要的,请更新一下问题,这样我才能给你更好的答案。

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

撰写回答