【问题标题】:How to Download Files using Python?如何使用 Python 下载文件?
【发布时间】:2010-12-09 21:26:47
【问题描述】:

大家好。我是 Python 新手,在 CentOS 上使用 Python 2.5。

我需要下载像WGET 这样的文件。

我已经做了一些搜索,并且有一些解决方案,一个明显的方法是:

import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
output = open('test.mp3','wb')
output.write(mp3file.read())
output.close()

这很好用。但我想知道,如果 mp3 文件非常大,比如 1Gb、2Gb 甚至更大。这段代码 sn-p 还能用吗?有没有更好的方法在 Python 中下载大文件,也许有像WGET 这样的进度条。

非常感谢!

【问题讨论】:

标签: python linux command-line centos wget


【解决方案1】:

有一个更简单的方法:

import urllib
urllib.urlretrieve("http://www.example.com/songs/mp3.mp3", "/home/download/mp3.mp3")

【讨论】:

    【解决方案2】:

    对于非常大的文件,您的代码将使用大量内存,因为您一次将整个文件加载到内存中。分块读写数据可能会更好:

    from __future__ import with_statement
    import urllib2
    mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
    with open('test.mp3','wb') as output:
        while True:
            buf = mp3file.read(65536)
            if not buf:
                break
            output.write(buf)
    

    【讨论】:

      【解决方案3】:

      那为什么不直接打电话给wget呢?

      import os
      os.system ("wget http://www.example.com/songs/mp3.mp3")
      

      【讨论】:

      • 谢谢。这种方法安全吗?似乎很有可能导致系统崩溃......因为据我所知,很少有人使用这种方法。
      • 而且好像没有办法知道wget方法是否成功。请查看此页面:http://linux.byexamples.com/archives/366/python-how-to-run-a-command-line-within-python/
      • @DocWiki 我更喜欢curl 本人而不是wget。不过,系统调用始终是一个棘手的命题。我自己投票给@Paul 的urlretrieve 回答。
      • 这也有缺点(取决于你在做什么)它需要 wget——即与纯 Python 解决方案不同,它无法在 Windows 上运行。
      【解决方案4】:

      您当前的代码将在写入磁盘之前将整个流读入内存。因此,对于文件大于可用内存的情况,您会遇到问题。

      要解决此问题,您可以一次读取块并将它们写入文件。


      (复制自Stream large binary files with urllib2 to file

      req = urllib2.urlopen(url)
      CHUNK = 16 * 1024
      with open(file, 'wb') as fp:
        while True:
          chunk = req.read(CHUNK)
          if not chunk: break
          fp.write(chunk)
      

      “对各种 CHUNK 大小进行一些实验,以找到满足您要求的“最佳位置”。”

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-13
        • 2021-09-25
        • 1970-01-01
        • 2023-04-06
        • 2012-12-07
        相关资源
        最近更新 更多