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
这个错误是因为 gzip 模块在写入压缩文件时需要字节(bytes)对象,而 plaintext 是一个字符串(str)对象。你需要在写入前将字符串编码为字节。以下是修改后的代码:
gzip
plaintext
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')
gzip.open(filename + ".gz", "wb")
wb
这样修改后,代码应该能正确地将输入的文本压缩并保存到指定的 gzip 文件中。