小能豆

TypeError: 'str' does not support the buffer interface

javascript

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

阅读 55

收藏
2024-07-13

共1个答案

小能豆

这个错误是因为 gzip 模块在写入压缩文件时需要字节(bytes)对象,而 plaintext 是一个字符串(str)对象。你需要在写入前将字符串编码为字节。以下是修改后的代码:

import gzip

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.encode('utf-8'))  # 将字符串编码为字节

解释:

  • plaintext.encode('utf-8'): 这会将字符串 plaintext 使用 UTF-8 编码转换为字节(bytes),这对于 gzip 模块写入压缩文件是必须的。
  • gzip.open(filename + ".gz", "wb"): wb 模式以二进制写入模式打开文件,这对于写入字节数据是必要的。

这样修改后,代码应该能正确地将输入的文本压缩并保存到指定的 gzip 文件中。

2024-07-13