Slava
Slava

Reputation: 1524

modify gzipped file with python

I am trying to modify the gzipped file. Here is my code:

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)

I removed all modifications, only left the read and write. On output I get the empty gzipped file. What's wrong with this? (Python 2.7.6, Linux)

Upvotes: 1

Views: 758

Answers (1)

Lim H.
Lim H.

Reputation: 10050

You need to point to the beginning of the temporary file after copy:

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

Upvotes: 2

Related Questions