Following tutorials and examples found in blogs and in other threads here, it appears that the way to write to a .gz file is to open it in binary mode and write the string as is:

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

I tried it, and got the following exception:

  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'

So I tried opening the file in text mode:

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

But I got the same error:

  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'

How can this problem be addressed in Python3?

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.