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

Python使用gzip读取.gz文件时出现AttributeError报错求助

解决gzip模块逐行读取.gz文件时的AttributeError问题

问题重现

在Linux系统的Python 3.10环境下,尝试逐行读取.gz文件时触发报错,错误信息如下:

AttributeError: 'GzipFile' object has no attribute '_buffer'

完整报错栈:

File "/home/user/path/to/example.py", line 40, in run
    for line in handle:
File "/home/user/.conda/envs/py38/lib/python3.10/gzip.py", line 399, in readline
    return self._buffer.readline(size)
AttributeError: 'GzipFile' object has no attribute '_buffer'

使用的代码:

import gzip

handle = gzip.open("path/to/file.txt.gz", "w")
for line in handle:
    print(line)

问题原因

核心错误是文件打开模式不匹配:你使用了写模式"w"打开文件,而写模式下的GzipFile对象仅支持写入操作,不会初始化读取所需的_buffer属性,因此尝试遍历读取时会触发属性不存在的错误。

解决方案

将文件打开模式改为读模式,推荐使用以下两种方式:

方式1:文本读模式(推荐)

使用"rt"模式打开,Python会自动完成字节到字符串的解码,直接读取文本行:

import gzip

# 用with语句自动管理文件句柄,避免资源泄漏
with gzip.open("path/to/file.txt.gz", "rt") as handle:
    for line in handle:
        print(line.strip())  # 可选:去除行尾换行符

方式2:二进制读模式

如果需要手动控制编码,可使用基础读模式"r",读取后自行解码:

import gzip

with gzip.open("path/to/file.txt.gz", "r") as handle:
    for line in handle:
        print(line.decode("utf-8").strip())  # 按指定编码解码为字符串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:00:56