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,那么string与Python2的类型不同.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'))

另外,不要使用像stringfile这样的变量名称,因为它们是模块或函数的名称.

EDIT @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)

Python相关问答推荐

Altair -箱形图边界设置为黑色,中线设置为红色

替换字符串中的点/逗号,以便可以将其转换为浮动

将numpy矩阵映射到字符串矩阵

Python主进程和分支进程如何共享gc信息?

请从Python访问kivy子部件的功能需要帮助

在Pandas 日历中插入一行

如何根据另一列值用字典中的值替换列值

如何使用Python将工作表从一个Excel工作簿复制粘贴到另一个工作簿?

Pytest两个具有无限循环和await命令的Deliverc函数

删除所有列值,但判断是否存在任何二元组

' osmnx.shortest_track '返回有效源 node 和目标 node 的'无'

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

使用setuptools pyproject.toml和自定义目录树构建PyPi包

在Python中动态计算范围

如何在Python中找到线性依赖mod 2

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

Pandas Data Wrangling/Dataframe Assignment

如何使regex代码只适用于空的目标单元格

幂集,其中每个元素可以是正或负""""

导入错误:无法导入名称';操作';