You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

低内存设备使用Python GZIP压缩大型CSV文件的高效方案问询

大体积CSV流压缩优化方案

原代码慢的核心原因

  • Python内置gzip模块为纯Python实现的单线程压缩,性能较低
  • shutil.copyfileobj默认缓冲区仅16KB,大文件读写时IO交互次数过多,拖慢速度

无额外依赖的快速优化

直接调整缓冲区大小即可获得明显提速,保持原逻辑不变、无需安装第三方库,适合低配置环境:

import gzip
import shutil

BUFFER_SIZE = 1 * 1024 * 1024  # 1MB缓冲区,可根据虚拟机内存调整为2/4MB
with open('file_to_be_compressed.csv', 'rb') as f_in:
    with gzip.open('test_out.csv.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out, length=BUFFER_SIZE)

更高性能的压缩方案(需安装第三方库)

方案1:保持gzip格式兼容,用ISA-L加速

使用python-isal库,基于硬件加速指令实现gzip压缩,单线程性能是内置gzip的2-3倍,CPU占用更低,适合低配置虚拟机:

  1. 安装依赖:pip install python-isal
  2. 代码仅需修改导入语句即可:
from isal import igzip
import shutil

BUFFER_SIZE = 1 * 1024 * 1024
with open('file_to_be_compressed.csv', 'rb') as f_in:
    with igzip.open('test_out.csv.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out, length=BUFFER_SIZE)

方案2:更高压缩率+更快速度,使用zstd格式

如果目标端支持zstd格式解压,推荐使用zstandard压缩,同等压缩率下速度比gzip快3-5倍,可自由调整压缩级别平衡速度和文件体积:

  1. 安装依赖:pip install zstandard
  2. 示例代码:
import zstandard as zstd
import shutil

BUFFER_SIZE = 1 * 1024 * 1024
# 压缩级别调整范围1-22,数值越小速度越快、压缩率越低,低配置环境推荐设为3-5
cctx = zstd.ZstdCompressor(level=3)
with open('file_to_be_compressed.csv', 'rb') as f_in:
    with cctx.stream_writer(open('test_out.csv.zst', 'wb')) as f_out:
        shutil.copyfileobj(f_in, f_out, length=BUFFER_SIZE)

适配批量文件处理的Pipeline逻辑

以下示例直接对接你已有的文件列表逻辑,完成批量压缩后可直接调用上传逻辑:

import os
from isal import igzip
import shutil

BUFFER_SIZE = 1 * 1024 * 1024
# 你已拉取到的待处理文件列表
file_list = ["file1.csv", "file2.csv", "file3.csv"]
compressed_files = []

for src_path in file_list:
    dst_path = f"{src_path}.gz"
    # 流式压缩,不占用过多内存
    with open(src_path, 'rb') as f_in:
        with igzip.open(dst_path, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out, length=BUFFER_SIZE)
    compressed_files.append(dst_path)

# 后续可直接遍历compressed_files列表执行上传逻辑

低配置虚拟机注意事项

  • 不建议使用多线程压缩工具(如pigz),避免CPU占满导致整个Pipeline任务阻塞
  • 缓冲区大小不要超过虚拟机空闲内存的1/10,避免触发内存交换拖慢速度
  • 压缩完成后可同步删除源文件,释放磁盘空间

内容的提问来源于stack exchange,提问作者Jamalan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:06:03