怎么用Python快速下载大文件

其他教程   发布日期:2025年03月28日   浏览次数:85

本篇内容介绍了“怎么用Python快速下载大文件”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

方法一

使用以下流式代码,无论下载文件的大小如何,Python 内存占用都不会增加:

  1. def download_file(url):
  2. local_filename = url.split('/')[-1]
  3. # 注意传入参数 stream=True
  4. with requests.get(url, stream=True) as r:
  5. r.raise_for_status()
  6. with open(local_filename, 'wb') as f:
  7. for chunk in r.iter_content(chunk_size=8192):
  8. f.write(chunk)
  9. return local_filename

如果你有对 chunk 编码的需求,那就不该传入 chunk_size 参数,且应该有 if 判断。

  1. def download_file(url):
  2. local_filename = url.split('/')[-1]
  3. # 注意传入参数 stream=True
  4. with requests.get(url, stream=True) as r:
  5. r.raise_for_status()
  6. with open(local_filename, 'w') as f:
  7. for chunk in r.iter_content():
  8. if chunk:
  9. f.write(chunk.decode("utf-8"))
  10. return local_filename

iter_content[1] 函数本身也可以解码,只需要传入参数 decode_unicode = True 即可。另外,搜索公众号顶级Python后台回复“进阶”,获取一份惊喜礼包。

请注意,使用 iter_content 返回的字节数并不完全是 chunk_size,它是一个通常更大的随机数,并且预计在每次迭代中都会有所不同。

方法二

使用 Response.raw[2] 和 shutil.copyfileobj[3]

  1. import requests
  2. import shutil
  3. def download_file(url):
  4. local_filename = url.split('/')[-1]
  5. with requests.get(url, stream=True) as r:
  6. with open(local_filename, 'wb') as f:
  7. shutil.copyfileobj(r.raw, f)
  8. return local_filename

这将文件流式传输到磁盘而不使用过多的内存,并且代码更简单。

注意:根据文档,Response.raw 不会解码,因此如果需要可以手动替换 r.raw.read 方法

  1. response.raw.read = functools.partial(response.raw.read, decode_content=True)

速度

方法二更快。方法一如果 2-3 MB/s 的话,方法二可以达到近 40 MB/s。

以上就是怎么用Python快速下载大文件的详细内容,更多关于怎么用Python快速下载大文件的资料请关注九品源码其它相关文章!