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

读取.gz文件调用split报错TypeError: a bytes-like object is required, not 'str'

gzip读取文件触发TypeError的原因及解决办法

错误根源

gzip.open()默认采用二进制模式(rb)读取压缩文件,所以你循环中拿到的每一行line是bytes类型对象,而非普通字符串。bytes类型的split()方法要求传入的分隔符也必须是bytes类型(比如b" "),但你传的是字符串" ",类型不匹配就抛出了TypeError。

两种修复方案

方案一:直接以文本模式打开

调用gzip.open()时指定mode="rt",这样读取的内容直接是字符串,和处理普通文本文件逻辑一致:

import gzip
logfile = "sample.gz"
with gzip.open(logfile, mode="rt") as page:
    for line in page:
        line = line.strip()  # 去掉换行符,避免最后一个元素带换行标记
        string = line.split(" ")
        print(*string, sep=',')

方案二:先解码bytes为字符串

如果需要保留二进制读取模式,可以先把line解码成字符串再操作:

import gzip
logfile = "sample.gz"
with gzip.open(logfile) as page:
    for line in page:
        line_str = line.decode().strip()  # 解码为utf-8字符串,可根据文件编码调整
        string = line_str.split(" ")
        print(*string, sep=',')

最终预期输出

两种方案运行后都会得到:

This,is,first,line,of,sample,gz,file.
This,is,second,line,of,sample,gz,file.

内容的提问来源于stack exchange,提问作者data-bite

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:10:28