按照博客和其他线程中的教程和示例,似乎写入.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中解决此问题?
答案 0 :(得分:9)
mode='wb'
写入以二进制模式打开的文件时,必须写入字节,而不是字符串。使用str.encode
编码您的字符串:
with gzip.open('file.gz', 'wb') as f:
f.write('Hello world!'.encode())
mode='wt'
(由OP找到)或者,当您在wt
(显式文本)模式下打开文件时,可以在文件中写入字符串:
with gzip.open('file.gz', 'wt') as f:
f.write('Hello world!')
documentation有几个方便的使用示例。