将大型二进制文件与urllib2流文件 [英] Stream large binary files with urllib2 to file
本文介绍了将大型二进制文件与urllib2流文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
fp = open(file, 'wb')
req = urllib2.urlopen(url)
在req中的行:
fp.write(行)
fp.close()
这个工作,但它下载相当慢。有更快的方法吗? (文件很大,所以我不想让它们在内存中。)
解决方案
没有理由一行一行(小块并且需要Python找到你的线路结束!),只是在更大的块中块,例如:
from urllib.request import urlopen#Python 3
response = urlopen(url)
CHUNK = 16 * 1024
with打开(文件'wb')为f:
,而True:
chunk = response.read(CHUNK)
如果不是chunk:
break
f.write (chunk)
使用各种CHUNK尺寸进行实验,以根据您的要求找到最佳点。
I use the following code to stream large files from the Internet into a local file:
fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
fp.write(line)
fp.close()
This works but it downloads quite slowly. Is there a faster way? (The files are large so I don't want to keep them in memory.)
解决方案
No reason to work line by line (small chunks AND requires Python to find the line ends for you!-), just chunk it up in bigger chunks, e.g.:
# 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)
Experiment a bit with various CHUNK sizes to find the "sweet spot" for your requirements.
这篇关于将大型二进制文件与urllib2流文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文