将文本写入gzip文件

Agv*_*uva 12 python gzip file python-3.x

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

import gzip
with gzip.open('file.gz', 'wb') as f:
    f.write('Hello world!')
Run Code Online (Sandbox Code Playgroud)

我试了一下,得到以下异常:

  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'
Run Code Online (Sandbox Code Playgroud)

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

import gzip
with gzip.open('file.gz', 'w') as f:
    f.write('Hello world!')
Run Code Online (Sandbox Code Playgroud)

但我得到了同样的错误:

  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'
Run Code Online (Sandbox Code Playgroud)

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

cs9*_*s95 16

mode='wb'

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

with gzip.open('file.gz', 'wb') as f:
    f.write('Hello world!'.encode())
Run Code Online (Sandbox Code Playgroud)

mode='wt'

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

with gzip.open('file.gz', 'wt') as f:
    f.write('Hello world!')
Run Code Online (Sandbox Code Playgroud)

文档有几个方便的使用示例.

  • @Sven 这个例子是为了演示如何通过变量编写字符串——然后你必须调用 string.encode() 。我认为这样解释会更容易。 (7认同)