您现在的位置是:亿华云 > 应用开发
Python 下载大文件,哪种方式速度更快!
亿华云2025-10-03 06:40:37【应用开发】6人已围观
简介通常,我们都会用 requests 库去下载,这个库用起来太方便了。方法一使用以下流式代码,无论下载文件的大小如何,Python 内存占用都不会增加:def download_file(url):lo
通常,下载我们都会用 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_filenameiter_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
很赞哦!(7)
上一篇: 外媒:微软将推出首款AI芯片,以减少对英伟达的依赖
下一篇: 评估新的数据中心计算范式