Python 将文本写入gzip文件

Python 将文本写入gzip文件,python,python-3.x,file,gzip,Python,Python 3.x,File,Gzip,以下是博客和其他线程中的教程和示例,似乎写入.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: mem

以下是博客和其他线程中的教程和示例,似乎写入
.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
(显式文本)模式下打开文件时,可以将字符串写入文件:


有几个简单的用法示例。

而不是
“Hello world!”。encode()
只需编写
b'Hello world!'@Sven该示例演示如何通过变量编写字符串——然后必须调用string.encode()。我想这样解释会更容易些。
with gzip.open('file.gz', 'wt') as f:
    f.write('Hello world!')