TypeError:“Str”不支持缓冲区接口

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


鸿蒙传说
浏览 534回答 3
3回答

狐的传说

这个问题有一个更容易解决的办法。您只需添加一个t到模式,所以它变成wt..这导致Python以文本文件的形式打开文件,而不是二进制文件。一切都会正常的。完整的程序如下:plaintext&nbsp;=&nbsp;input("Please&nbsp;enter&nbsp;the&nbsp;text&nbsp;you&nbsp;want&nbsp;to&nbsp;compress")filename&nbsp;=&nbsp;input("Please&nbsp;enter&nbsp;the&nbsp;desired&nbsp;filename") with&nbsp;gzip.open(filename&nbsp;+&nbsp;".gz",&nbsp;"wt")&nbsp;as&nbsp;outfile: &nbsp;&nbsp;&nbsp;&nbsp;outfile.write(plaintext)

忽然笑

如果不明确地将Python 3‘字符串’序列化为字节,则不能将其序列化为某种编码。outfile.write(plaintext.encode('utf-8'))可能是你想要的。这也适用于python2.x和3.x。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python