如何使用Python提取.gz zipfile?

2024-04-16 08:47:25 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用Python提取.gz Zipe文件

示例文件: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()

Tags: 文件iphttp示例closeaswwwwith
1条回答
网友
1楼 · 发布于 2024-04-16 08:47:25

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

如果已足够,您还可以选择使用提供多个,-shearedwith_itemwith-statement功能来避免嵌套,即:

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

请记住,以上要求Python3.3或更新版本才能工作

相关问题 更多 >