+4 votes
in Programming Languages by (17.7k 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

0 votes
by (35.8k points)

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
 

...