如何使用 Python 提取 .gz 压缩文件?

How to extract a .gz zipfile using Python?

如何使用 Python 提取 .gz 压缩文件?

示例文件:http://www.o-bible.com/download/kjv.gz(先下载脚本才能运行)

我的代码有效,但我认为有更好的方法。欢迎提出建议!

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 构造是一般使用所以你不必自己关闭资源,所以这部分代码:

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())

就足够了,您也可以选择避免嵌套使用提供 with-statement 多个 ,-sheared with_item 的能力,即:

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())

虽然这会导致行变长,但请随意使用更短的行或更长的行,但要减少嵌套。

gzip.open 在文本模式下为您换行 io.TextIOWrapper 因此您的代码可以简化为:

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

请记住,以上要求 python 3.3 或更新版本才能工作。