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

如何使用writelines进行gzip文件压缩?压缩后无法解压该如何解决

问题根因与修复方案

现有代码错误点

  • 第一版代码问题:
    1. 读取源文件时硬编码了"path/to/file"路径,没有读取testList中对应路径的实际文件
    2. gzip.open()的with代码块执行结束后,会自动关闭压缩文件对象zipped_file,此时调用upload_fileobj读取已关闭的文件,只能获取到空内容
    3. 即使文件未关闭,写入完成后文件指针位于文件末尾,直接读取也会返回空
  • 第二版修改后代码问题:
    1. 变量调用错误:f_out是gzip文件对象,本身没有upload_fileobj方法,该方法属于S3的bucket实例;同时代码中引用的zipped_file变量未定义
    2. 仍然存在文件关闭后操作的问题,无法读取到压缩文件的实际内容
    3. 上传到S3的文件Key没有带.gz后缀,用户下载后可能因缺少后缀导致系统无法识别压缩格式

修复代码

推荐直接使用bucket.upload_file接口上传本地已生成的压缩文件,无需手动处理文件指针逻辑,出错概率更低:

import gzip
import shutil

for i in testList:
    # S3存储的Key添加.gz后缀,避免下载后无法识别格式
    s3_key = i.replace("/tmp/files/", "") + ".gz"
    local_gz_path = i + '.gz'
    # 执行本地gzip压缩
    with open(i, 'rb') as f_in:
        with gzip.open(local_gz_path, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
    # 直接上传本地压缩文件到S3
    bucket.upload_file(
        Filename=local_gz_path,
        Key=s3_key,
        ExtraArgs={'ContentType': "application/gzip"}
    )

如果需要使用upload_fileobj接口,可在压缩完成后重新打开本地压缩文件再上传:

import gzip
import shutil

for i in testList:
    s3_key = i.replace("/tmp/files/", "") + ".gz"
    local_gz_path = i + '.gz'
    # 执行本地gzip压缩
    with open(i, 'rb') as f_in:
        with gzip.open(local_gz_path, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
    # 重新打开本地压缩文件上传
    with open(local_gz_path, 'rb') as f_zipped:
        bucket.upload_fileobj(
            Fileobj=f_zipped,
            Key=s3_key,
            ExtraArgs={'ContentType': "application/gzip"}
        )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:24:03