我使用以下代码将大型文件从Internet流化为本地文件:

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

这可行,但下载速度很慢。有没有更快的方法? (文件很大,所以我不想将它们保留在内存中。)

最佳答案

没有理由一行一行地工作(小块并且需要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)

尝试各种CHUNK尺寸,找到适合您需求的“最佳位置”。

关于python - 使用urllib2将大型二进制文件流式传输到文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1517616/

10-11 21:58
查看更多