首頁  >  文章  >  後端開發  >  Python 下載大文件,哪種方式速度更快!

Python 下載大文件,哪種方式速度更快!

王林
王林轉載
2023-04-14 21:19:012038瀏覽

Python 下載大文件,哪種方式速度更快!

通常,我們都會用 requests 函式庫去下載,而這個函式庫用起來太方便了。

方法一

使用以下串流程式碼,無論下載檔案的大小如何,Python 記憶體佔用都不會增加:

def download_file(url):
local_filename = url.split('/')[-1]
# 注意传入参数 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 參數,而且應該有if 判斷。

def download_file(url):
local_filename = url.split('/')[-1]
# 注意传入参数 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] 函數本身也可以解碼,只需要傳入參數 decode_unicode = True 即可。另外,搜尋公眾號頂級Python後台回复“進階”,獲取驚喜禮包。

請注意,使用 iter_content 傳回的位元組數並不完全是 chunk_size,它是一個通常更大的隨機數,並且預計在每次迭代中都會有所不同。

方法二

使用 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

這將檔案串流傳輸到磁碟而不使用過多的內存,並且程式碼更簡單。

注意:根據文檔,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

#

以上是Python 下載大文件,哪種方式速度更快!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除