+5 votes
in Programming Languages by (71.8k points)
edited by
I want to text data (tab-separated) to a gzip file, instead of a text file. How can I open a gzip file in write mode and write the data to it?

1 Answer

+1 vote
by (353k points)
selected by
Best answer

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:

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:

Output: apple    banana    monkey

with gzip.open(filename, 'rt') as fo:
    v = fo.readline()

Output: apple    banana    monkey

Related questions

+5 votes
1 answer
asked Jul 27, 2021 in Programming Languages by kush (40.5k points)
+2 votes
1 answer