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

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:Python32libgzip.py", line 312, in write
    self.crc = zlib.crc32(data, self.crc) & 0xffffffff
TypeError: 'str' does not support the buffer interface

如果您使用Python3x,那么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而这些名称是模块或函数的名称。

编辑@汤姆

是的,非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)

这个问题有一个更简单的解决方案。

你只需要添加一个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)

你不能将一个Python 3'字符串'序列化为字节,而不需要向某些编码进行明确的转换。

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

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

链接地址: http://www.djcxy.com/p/87207.html

上一篇: TypeError: 'str' does not support the buffer interface

下一篇: Check if a string is null or empty in XSLT