暂时解压缩文件的最佳(最"pythonic")方式

Bi *_*ico 7 python gzip

我需要暂时创建一些文件的解压缩版本.我见过人们zcat somefile.gz > /tmp/somefile用bash 做的,所以我在python中创建了这个简单的函数:

from subprocess import check_call
def unzipto(zipfile, tmpfile):
    with open(tmpfile, 'wb') as tf:
        check_call(['zcat', zipfile], stdout=tf)
Run Code Online (Sandbox Code Playgroud)

但是使用zcat和check_call对我来说似乎很苛刻,我想知道是否有更多的"pythonic"方法来做到这一点.

谢谢你的帮助

Fre*_*Foo 16

gzip.open(zipfile).read() 将以单个字符串为您提供文件的内容.

with open(tmpfile, "wb") as tmp:
    shutil.copyfileobj(gzip.open(zipfile), tmp)
Run Code Online (Sandbox Code Playgroud)

将内容放在临时文件中.

  • 除此之外,还有一个 python 模块来处理临时文件和目录的创建和删除(https://docs.python.org/library/tempfile.html)。对于这个案例来说是非常有帮助的。 (2认同)

Abh*_*jit 6

您是否考虑过使用zlibgziptarfile.