使用urllib2将大型二进制文件流式传输到文件

hoj*_*oju 53 python streaming file urllib2

我使用以下代码将大型文件从Internet流式传输到本地文件:

fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
    fp.write(line)
fp.close()
Run Code Online (Sandbox Code Playgroud)

这有效,但下载速度很慢.有更快的方法吗?(文件很大,所以我不想把它们留在内存中.)

Ale*_*lli 105

没有理由一行一行地工作(小块并且需要Python来为你找到行结束! - ),只需将它放入更大的块中,例如:

# from urllib2 import urlopen # Python 2
from urllib.request import urlopen # Python 3

response = urlopen(url)
CHUNK = 16 * 1024
with open(file, 'wb') as f:
    while True:
        chunk = response.read(CHUNK)
        if not chunk:
            break
        f.write(chunk)
Run Code Online (Sandbox Code Playgroud)

尝试使用各种CHUNK尺寸来找到符合您要求的"最佳位置".

  • russenreaktor,使用with open(...)as ...:在离开with语句时调用了一个隐式close(). (8认同)
  • 在for it中使用`for chunk(lambda:f.read(CHUNK),''):`而不是`而True:`也是pythonic. (8认同)
  • 它对我有用.但我认为fp.close()仍然缺失 (3认同)

Tia*_*ago 64

你也可以使用shutil:

import shutil
try:
    from urllib.request import urlopen # Python 3
except ImportError:
    from urllib2 import urlopen # Python 2

def get_large_file(url, file, length=16*1024):
    req = urlopen(url)
    with open(file, 'wb') as fp:
        shutil.copyfileobj(req, fp, length)
Run Code Online (Sandbox Code Playgroud)


lio*_*ori 6

我曾经使用过mechanize模块及其Browser.retrieve()方法.在过去,它占用了100%的CPU并且下载的东西非常缓慢,但最近的一些版本修复了这个错误并且工作得非常快.

例:

import mechanize
browser = mechanize.Browser()
browser.retrieve('http://www.kernel.org/pub/linux/kernel/v2.6/testing/linux-2.6.32-rc1.tar.bz2', 'Downloads/my-new-kernel.tar.bz2')
Run Code Online (Sandbox Code Playgroud)

Mechanize基于urllib2,所以urllib2也可以有类似的方法......但我现在找不到任何东西.