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
如果您使用 Python3x thenstring与 Python 2.x 的类型不同,则必须将其转换为字节(对其进行编码)。
string
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'))
也不要使用变量名,比如stringorfile而那些是模块或函数的名称。
file
编辑@Tom
是的,非 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)