简体   繁体   English

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

[英]Best (most “pythonic”) way to temporarily unzip a file

I need to temporarily create an unzipped version of some files. 我需要暂时创建一些文件的解压缩版本。 I've seen people do zcat somefile.gz > /tmp/somefile in bash, so I made this simple function in python: 我见过人们在bash中做zcat somefile.gz > /tmp/somefile ,所以我在python中创建了这个简单的函数:

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

But using zcat and check_call seems hackish to me and I was wondering if there was more "pythonic" way to do this. 但是使用zcat和check_call对我来说似乎很苛刻,我想知道是否有更多的“pythonic”方法来做到这一点。

Thanks for your help 谢谢你的帮助

gzip.open(zipfile).read() will give you the contents of the file in a single string. gzip.open(zipfile).read()将在单个字符串中提供文件的内容。

with open(tmpfile, "wb") as tmp:
    shutil.copyfileobj(gzip.open(zipfile), tmp)

will put the contents in a temporary file. 将内容放在临时文件中。

您是否考虑过使用zlibgziptarfile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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