Does Python 3 gzip closes the fileobj?

Viewed 225

The gzip docs for Python 3 states that

Calling a GzipFile object’s close() method does not close fileobj, since you might wish to append more material after the compressed data

Does this mean that the gzip file handler f_in is not closed if we do the following

import gzip
import shutil
with gzip.open('/home/joe/file.txt.gz', 'rb') as f_in:
    with open('/home/joe/file.txt', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

If so, will this cause a leak if this code is executed multiple times?

1 Answers

The warning about fileobj not being closed only applies when you open the file, and pass it to the GzipFile via the fileobj= parameter. When you pass only a filename, GzipFile "owns" the file handle and will also close it.

Related