Python-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:\Python32\lib\gzip.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'))

也不要使用像string或那样的变量file名作为模块或函数的名称。

是的,非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-TypeError:“ str”不支持缓冲区接口 的全部内容, 来源链接: utcz.com/qa/412014.html

回到顶部