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
相关产品推荐
相关产品推荐

