0

Writing to the start of a txt file can be achieved like this:

with open('foo.txt', 'wt') as outfn:
    for i in range(10):
        outfn.write('{}\n'.format(i))

with open('foo.txt', 'r+') as fn:
    content = fn.read()
    fn.seek(0, 0)
    fn.write('foo\n{}'.format(content))

However, when I try to write to the start of a gzip file:

import gzip 

with gzip.open('foo.txt.gz', 'wt') as outfn:
    for i in range(10):
        outfn.write('{}\n'.format(i))

with gzip.open('foo.txt.gz', 'r+') as fn:
    content = fn.read()
    fn.seek(0, 0)
    fn.write('foo\n{}'.format(content))

The following error is thrown:

OSError: [Errno 9] write() on read-only GzipFile object

I tried multiple alternatives, but couldn't come up with a decent way to write text to the start of a gzip file.

pr94
  • 1,263
  • 12
  • 24

2 Answers2

1

I don't think that gzip.open has a '+' option the same way a normal file open does. See here: gzip docs

What exactly are you trying to do by writing to the beginning of the file? It may be easier to open the file again and overwrite it.

mpw2
  • 148
  • 8
  • In the first part of the code I have to write a large amount of text to the gzip file. I am using a for loop that. Then in second part I have to write to the start of the gzipped file the number of lines that are appended to the file. Perhaps you have a better strategy? – pr94 Aug 05 '20 at 10:35
  • If you want the number of lines to be gzipped as well then you could try writing that to a separate file and then concatenating the two files. Similar to [this answer.](https://stackoverflow.com/questions/31289449/append-one-line-at-the-top-of-huge-gzip-file) – mpw2 Aug 05 '20 at 11:06
  • If you want to do everything in the python code you can probably find other answers to do this. Here is one [example.](https://stackoverflow.com/questions/18208898/concatenate-gzipped-files-with-python-on-windows) – mpw2 Aug 05 '20 at 11:07
  • Yeah sure, I can definitely go for that. I was just wondering if someone would have an elegant way to directly implement this in the code above or a way akin to that. Nevertheless +1 for the effort of thinking along, thanks! – pr94 Aug 05 '20 at 11:11
0

I have come up with this solution:

import gzip 

content = str()
for i in range(10):
    content += '{}\n'.format(i)

with gzip.open('foo.txt.gz', 'wt') as outfn:
    outfn.write('foo\n{}'.format(content))
pr94
  • 1,263
  • 12
  • 24