【问题标题】:Python gzip gives error and asks for bytes like inputPython gzip 给出错误并要求输入像输入这样的字节
【发布时间】:2017-10-12 11:57:58
【问题描述】:

我无法让它工作

import gzip
content = "Lots of content here"
f = gzip.open('file.txt.gz', 'a', 9)
f.write(content)
f.close()

我得到输出:

============== RESTART: C:/Users/Public/Documents/Trial_vr06.py ==============
Traceback (most recent call last):
  File "C:/Users/Public/Documents/Trial_vr06.py", line 4, in <module>
    f.write(content)
  File "C:\Users\SONID\AppData\Local\Programs\Python\Python36\lib\gzip.py", line 260, in write
    data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'

这是在Python Gzip - Appending to file on the flyIs it possible to compress program output within python to reduce output file's size? 的答案中链接的

我尝试过整数数据,但没有效果。这里有什么问题

【问题讨论】:

  • 这个link 有同样的问题。

标签: python file-io gzip


【解决方案1】:

默认gzip 流是二进制 (Python 3: gzip.open() and modes)。

在 Python 2 中没有问题,但 Python 3 在二进制流和文本流之间有所不同。

所以要么编码你的字符串(或者使用b前缀,如果它是像你的例子中的文字,并不总是可能的)

f.write(content.encode("ascii"))

或者只对文本更好:将gzip 流打开为文本

f = gzip.open('file.txt.gz', 'at', 9)

请注意,gzip 文件上的附加模式效率不高 (Python Gzip - Appending to file on the fly)

【讨论】:

  • 谢谢。这是仅针对 Py3.x 的更改吗?
【解决方案2】:

为了压缩你的字符串,它必须是一个二进制值。为了做到这一点,只需在字符串前面放一个“b”。这将告诉解释器将其读取为二进制值而不是字符串值。

content = b"Lots of content here"

https://docs.python.org/3/library/gzip.html

【讨论】:

  • 感谢您的回答。当我以后从程序的输出文件中读取这些数据时,会不会导致一些变化?
  • 您需要做的就是将标志设置为“rb”或其他一些表示二进制的形式,您将被设置为没有任何问题。
猜你喜欢
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多