使用 python 写入 gzip 文件的开头

Writing to start of gzip file with python

写入txt文件的开头可以这样实现:

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))

但是,当我尝试写入 gzip 文件的开头时:

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))

抛出以下错误:

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

我尝试了多种选择,但无法想出一个合适的方法来将文本写入 gzip 文件的开头。

我认为 gzip.open 没有像普通文件打开那样的“+”选项。看这里:gzip docs

你到底想通过写入文件的开头来做什么?再次打开文件并覆盖它可能会更容易。

我想到了这个解决方案:

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))