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

如何使用Python批量将多个txt文件压缩为gzip格式的.gz文件

Python批量gzip压缩txt文件实现方案
  • 直接用glob模块匹配所有.txt后缀文件,循环执行单文件压缩逻辑即可,使用with上下文管理器可自动处理文件开关,无需手动调用close()方法。

普通场景代码(适用于多数中小体积文件)

import gzip
import glob
import os

# 匹配当前目录下所有txt文件,需指定目录则修改路径为 "目标目录/*.txt" 即可
txt_file_list = glob.glob("*.txt")

for txt_file in txt_file_list:
    gz_file_name = txt_file + ".gz"
    with open(txt_file, "rb") as source_file, gzip.open(gz_file_name, "wb") as gz_file:
        gz_file.writelines(source_file)
    # 若压缩后无需保留原始txt文件,取消注释下行代码即可
    # os.remove(txt_file)

大文件适配场景代码(避免内存占用过高)

如果待压缩的txt文件体积超过1GB,推荐使用逐块读取的方式压缩:

import gzip
import glob
import os

# 单次读取块大小设置为10MB,可按需调整
READ_BLOCK_SIZE = 10 * 1024 * 1024
txt_file_list = glob.glob("*.txt")

for txt_file in txt_file_list:
    gz_file_name = txt_file + ".gz"
    with open(txt_file, "rb") as source_file, gzip.open(gz_file_name, "wb") as gz_file:
        while True:
            file_block = source_file.read(READ_BLOCK_SIZE)
            if not file_block:
                break
            gz_file.write(file_block)
    # 同样可添加删除原文件的逻辑
    # os.remove(txt_file)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:36:03