Python 下載大文件,哪種方式速度更快!
通常,我們都會(huì)用 requests 庫(kù)去下載,這個(gè)庫(kù)用起來太方便了。
方法一
使用以下流式代碼,無論下載文件的大小如何,Python 內(nèi)存占用都不會(huì)增加:
def download_file(url):
local_filename = url.split('/')[-1]
# 注意傳入?yún)?shù) stream=True
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
return local_filename
如果你有對(duì) chunk 編碼的需求,那就不該傳入 chunk_size 參數(shù),且應(yīng)該有 if 判斷。
def download_file(url):
local_filename = url.split('/')[-1]
# 注意傳入?yún)?shù) stream=True
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(local_filename, 'w') as f:
for chunk in r.iter_content():
if chunk:
f.write(chunk.decode("utf-8"))
return local_filename
iter_content[1] 函數(shù)本身也可以解碼,只需要傳入?yún)?shù) decode_unicode = True 即可。另外,搜索公眾號(hào)頂級(jí)Python后臺(tái)回復(fù)“進(jìn)階”,獲取一份驚喜禮包。
請(qǐng)注意,使用 iter_content 返回的字節(jié)數(shù)并不完全是 chunk_size,它是一個(gè)通常更大的隨機(jī)數(shù),并且預(yù)計(jì)在每次迭代中都會(huì)有所不同。
方法二
使用 Response.raw[2] 和 shutil.copyfileobj[3]
import requests
import shutil
def download_file(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
這將文件流式傳輸?shù)酱疟P而不使用過多的內(nèi)存,并且代碼更簡(jiǎn)單。
注意:根據(jù)文檔,Response.raw 不會(huì)解碼,因此如果需要可以手動(dòng)替換 r.raw.read 方法
response.raw.read = functools.partial(response.raw.read, decode_content=True)
速度
方法二更快。方法一如果 2-3 MB/s 的話,方法二可以達(dá)到近 40 MB/s。
參考資料
[1]iter_content: https://requests.readthedocs.io/en/latest/api/#requests.Response.iter_content
[2]Response.raw: https://requests.readthedocs.io/en/latest/api/#requests.Response.raw
[3]shutil.copyfileobj: https://docs.python.org/3/library/shutil.html#shutil.copyfileobj