将文本写入 gzip 文件

Writing text to gzip file

按照博客和此处其他线程中的教程和示例,写入 .gz 文件的方法似乎是以二进制模式打开它并按原样写入字符串:

import gzip
with gzip.open('file.gz', 'wb') as f:
    f.write('Hello world!')

我试过了,出现以下异常:

  File "C:\Users\Tal\Anaconda3\lib\gzip.py", line 258, in write
    data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'

所以我尝试以文本模式打开文件:

import gzip
with gzip.open('file.gz', 'w') as f:
    f.write('Hello world!')

但是我得到了同样的错误:

  File "C:\Users\Tal\Anaconda3\lib\gzip.py", line 258, in write
    data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'

如何在 Python3 中解决这个问题?

mode='wb'

写入以二进制模式打开的文件时,必须写入字节,而不是字符串。使用 str.encode:

编码您的字符串
with gzip.open('file.gz', 'wb') as f:
    f.write('Hello world!'.encode())

mode='wt'

(由 OP 找到)或者,您可以在 wt(显式 text)模式下打开文件时将字符串写入文件:

with gzip.open('file.gz', 'wt') as f:
    f.write('Hello world!')

documentation 有几个方便的用法示例。