上条把妹之手 发表于 2018-9-19 16:30:46

TypeError: 'str' does not support the buffer interface

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

天使与魔鬼 发表于 2018-9-19 16:33:43

如果使用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)

德国骨科 发表于 2018-9-19 16:38:16

这个问题有一个更简单的解决方案。
您只需要在模式中添加一个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)

蛋蛋超人 发表于 2018-9-19 16:39:31

对于Python 3.x,你可以通过以下方式将文本转换为原始字节:
bytes("my data", "encoding")
例如:
bytes("attack at dawn", "utf-8")
将使用outfile.write返回对象

此间少年 发表于 2018-9-19 16:41:31

从py2切换到py3时,通常会发生此问题。在py2 plaintext中,字符串和字节数组都是类型。在py3 plaintext中只是一个字符串,并且outfile.write()方法在二进制模式下打开outfile时实际上采用了一个字节数组,因此引发了异常。更改输入以plaintext.encode('utf-8')解决问题。
在py2中,file.write的声明使它看起来像你传入一个字符串:file.write(str)。实际上你传入一个字节数组, file.write(bytes)。file.write(bytes)需要一个字节类型,并在py3中从你转换它的str中获取字节:
py3>> outfile.write(plaintext.encode('utf-8'))

污妖王 发表于 2018-9-19 16:42:44

你无法将Python 3'字符串'序列化为字节,而无需将explict转换为某些编码。
outfile.write(plaintext.encode('utf-8'))
可能是你想要的。这也适用于python 2.x和3.x.

www呵呵 发表于 2018-10-10 08:13:47

气氛真好啊,大家都很热心
页: [1]
查看完整版本: TypeError: 'str' does not support the buffer interface