TypeError: 'str'不支持缓冲区接口

272 投票
7 回答
350614 浏览
提问于 2025-04-16 14:38
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

7 个回答

43

在Python 3中,你不能直接把一个'字符串'转换成字节(bytes),必须先明确地转换成某种编码格式。

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

这可能就是你想要的。此外,这种方法在Python 2.x和3.x中都适用。

97

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

你只需要在模式中加一个 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)
300

如果你使用的是Python 3.x,那么string的类型和Python 2.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'))

另外,不要使用像stringfile这样的变量名,因为这些都是模块或函数的名称。

编辑 @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)

撰写回答