首页 > 解决方案 > gzip Python3无法将字节转换为字符串

问题描述

我有一个用 Python2.7 编写的解压缩函数

def unzip(text):
    try:
        return gzip.GzipFile(fileobj=StringIO(text)).read()
    except IOError:
        return text

使用 Python3.7 运行时,出现错误

TypeError: can't concat str to bytes

我试过了

将其更改为return gzip.GzipFile(fileobj=bytes(text, 'utf-8')).read()

但后来我得到:AttributeError: 'bytes' object has no attribute 'read'

标签: python

解决方案


StringIO生成字符串 ( str) 对象,需要相应地进行编码/解码。请参阅https://docs.python.org/3/library/io.html#text-io

在您的情况下,鉴于您正在处理您需要使用的二进制数据BytesIO。请参阅https://docs.python.org/3/library/io.html#binary-io

您不能bytes像预期的那样直接使用GzipFile带有read方法的类文件对象。

您的代码在 python 2 中运行而不在 python 3 中运行的原因是因为bytes并且str在 python 2 中是相同的。如果您的代码需要在两个版本中运行,那么您可能需要使用模块中的BytesIOio。请参阅https://docs.python.org/2.7/library/io.html#binary-io


推荐阅读