简体   繁体   中英

How to extract a .gz zipfile using Python?

How to extract a.gz zipefile using Python?

Example file: http://www.o-bible.com/download/kjv.gz (download first for script to work)

My code works, but I thing there is a better way. Suggestions welcome!

with open('file.txt', 'w') as file:
    with gzip.open('kjv.gz', 'rb') as ip:
        with io.TextIOWrapper(ip, encoding='utf-8') as decoder:
            file.write(decoder.read())
    ip.close()
file.close()

with construct are generally use so you do not have to close resources yourself, so this part of code:

with open('file.txt', 'w') as file:
    with gzip.open('kjv.gz', 'rb') as ip:
        with io.TextIOWrapper(ip, encoding='utf-8') as decoder:
            file.write(decoder.read())

is sufficient, you might also elect to avoid nesting using ability to provide with-statement with multiple , -sheared with_item s ie:

with open('file.txt', 'w') as file, gzip.open('kjv.gz', 'rb') as ip, io.TextIOWrapper(ip, encoding='utf-8') as decoder:
    file.write(decoder.read())

Though this result in long line, so feel free to use either more short lines or longer line but less nesting.

gzip.open does, in text mode, wrapping in io.TextIOWrapper for you so your code can be simplified to:

with open('file.txt', 'w') as file, gzip.open('kjv.gz', 'rt', encoding='utf-8') as ip:
    file.write(ip.read())

keep in mind that above requires python 3.3 or newer to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM