You can use the open() function of gzip library to open the file. Since you want to write text data, you need to use "wt" for text mode. Once you opened the file, you can use the write() function to write the data.
The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x' or 'xb' for binary mode, or 'rt', 'at', 'wt', or 'xt' for text mode. The default is 'rb'.
Here is an example:
import gzip
filename ="testfile.tsv.gz"
rec = "apple" + "\t" + "banana" + "\t" + "monkey" + "\n"
with gzip.open(filename, 'wt') as fo:
fo.write(rec)
To read the data from the above file, you can use the following codes:
with gzip.open(filename, 'rt') as fo:
for line in fo:
print(line)
Output: apple banana monkey
with gzip.open(filename, 'rt') as fo:
v = fo.readline()
print(v)
Output: apple banana monkey