python - 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'
解决方案
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 中是相同的。如果您的代码需要在两个版本中运行,那么您可能需要使用模块中的BytesIO
类io
。请参阅https://docs.python.org/2.7/library/io.html#binary-io。
推荐阅读
- c# - 如何使用 SkiaSharp 在 Xamarin 中创建简单的动画
- ada - Gnatchop 未解析文件
- angular - toString 的 ionic 4 最喜欢的问题并保存数据
- django - 使用 Django Rest Framework 计算对象
- python - 通过键列表在嵌套字典中附加(而不是替换)项目
- networking - 基于带有 PF_RING 的端口对入站流量进行优先级排序并将其路由到虚拟接口
- spring-batch - 在 spring 批处理应用程序上实现 graalvm 是否可以提高其性能
- node.js - 在腻子会话超时后,Angular 会话被终止
- sharepoint - 无法将共享点文件夹同步到本地设备
- javascript - Electron-forge 使我的 Windows 安装文件运行应用程序但不安装它