plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
    outfile.write(plaintext) 

上面的python代码给我以下错误:

Traceback (most recent call last):
  File "C:/Users/Ankur Gupta/Desktop/Python_works/gzip_work1.py", line 33, in <module>
    compress_string()
  File "C:/Users/Ankur Gupta/Desktop/Python_works/gzip_work1.py", line 15, in compress_string
    outfile.write(plaintext)
  File "C:\Python32\lib\gzip.py", line 312, in write
    self.crc = zlib.crc32(data, self.crc) & 0xffffffff
TypeError: 'str' does not support the buffer interface

当前回答

这个问题有一个更简单的解决办法。

你只需要在模式中添加一个t,这样它就变成了wt。这会导致Python以文本文件而不是二进制文件的形式打开文件。然后一切都会好起来的。

完整的程序变成这样:

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
    outfile.write(plaintext)

其他回答

如果使用Python3x,则string类型与python2不同。X时,必须将其转换为字节(编码)。

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
    outfile.write(bytes(plaintext, 'UTF-8'))

也不要使用变量名,如字符串或文件,而这些是模块或函数的名称。

编辑@Tom

是的,非ascii文本也被压缩/解压缩。我使用UTF-8编码的波兰字母:

plaintext = 'Polish text: ąćęłńóśźżĄĆĘŁŃÓŚŹŻ'
filename = 'foo.gz'
with gzip.open(filename, 'wb') as outfile:
    outfile.write(bytes(plaintext, 'UTF-8'))
with gzip.open(filename, 'r') as infile:
    outfile_content = infile.read().decode('UTF-8')
print(outfile_content)

对于Python 3。X你可以通过以下方式将文本转换为原始字节:

bytes("my data", "encoding")

例如:

bytes("attack at dawn", "utf-8")

返回的对象将与outfile.write一起工作。

如果不显式转换为某种编码,就不能将Python 3 'string'序列化为字节。

outfile.write(plaintext.encode('utf-8'))

可能是你想要的。这也适用于python 2。X和3.x。

>>> s = bytes("s","utf-8")
>>> print(s)
b's'
>>> s = s.decode("utf-8")
>>> print(s)
s

好吧,如果对你有用的话,可以删除烦人的'b'字符。如果有人有更好的想法,请建议我或随时在这里编辑我。我只是个新手

这个问题有一个更简单的解决办法。

你只需要在模式中添加一个t,这样它就变成了wt。这会导致Python以文本文件而不是二进制文件的形式打开文件。然后一切都会好起来的。

完整的程序变成这样:

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
    outfile.write(plaintext)