mode="wb"
When writing to a file opened in binary mode, you must write bytes, not string. Encode your string using str.encode
:
with gzip.open('file.gz', 'wb') as f:
f.write('Hello world!'.encode())
mode="wt"
(found by OP) Alternatively, you can write strings to your file when you open it in the wt
(explicit text) mode:
with gzip.open('file.gz', 'wt') as f:
f.write('Hello world!')
The documentation has a couple of handy examples on usage.