Python 下载大文件,哪种方式速度更快

转载:Python 下载大文件,哪种方式速度更快 (qq.com)

方法一

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

def download_file(url):
    local_filename = url.split('/')[-1]
    # 注意传入参数 stream=True
    with requests.get(url, stream=Trueas 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=Trueas 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 即可。

请注意,使用 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=Trueas 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

posted on   我和你并没有不同  阅读(249)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-08-27 keepalived 转载自:https://zhuanlan.zhihu.com/p/143295216
2020-08-27 redis 转码
2019-08-27 shell 学习笔记2
2019-08-27 python 编码规范
2018-08-27 java学习笔记
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示