Python 下載大文件,哪種方式速度更快!
通常,我們都會用 requests 庫去下載,這個庫用起來太方便了。
方法一
使用以下流式代碼,無論下載文件的大小如何,Python 內(nèi)存占用都不會增加:
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
如果你有對 chunk 編碼的需求,那就不該傳入 chunk_size 參數(shù),且應該有 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 即可。另外,搜索公眾號頂級Python后臺回復“進階”,獲取一份驚喜禮包。
請注意,使用 iter_content 返回的字節(jié)數(shù)并不完全是 chunk_size,它是一個通常更大的隨機數(shù),并且預計在每次迭代中都會有所不同。
方法二
使用 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)存,并且代碼更簡單。
注意:根據(jù)文檔,Response.raw 不會解碼,因此如果需要可以手動替換 r.raw.read 方法
response.raw.read = functools.partial(response.raw.read, decode_content=True)
速度
方法二更快。方法一如果 2-3 MB/s 的話,方法二可以達到近 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