Python-TypeError:“ str”不支持缓冲区接口

发布于 2021-02-02 23:20:36

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
关注者
0
被浏览
172
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    有一个解决此问题的简便方法。

    你只需要向t模式添加a 即可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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看