Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python 3 gzip closes the fileobj?

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?

like image 609
Athena Wisdom Avatar asked Aug 01 '26 05:08

Athena Wisdom


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.

like image 179
Ture Pålsson Avatar answered Aug 02 '26 20:08

Ture Pålsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!