使用 python 修改压缩文件

modify gzipped file with python

我正在尝试修改压缩文件。 这是我的代码:

with tempfile.TemporaryFile() as tmp:
    with gzip.open(fname, 'rb') as f:
        shutil.copyfileobj(f, tmp)
    # do smth here later
    with gzip.open(fname, 'wb') as f:
        shutil.copyfileobj(tmp, f)

我去掉了所有修改,只留下读写。在输出时,我得到空的 gzip 文件。这有什么问题吗? (Python 2.7.6, Linux)

复制后需要指向临时文件的开头:

with tempfile.TemporaryFile() as tmp:
    with gzip.open(fname, 'rb') as f:
        shutil.copyfileobj(f, tmp)
        tmp.seek(0)