Bi Rico
Bi Rico

Reputation: 25833

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:

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.

Thanks for your help

Upvotes: 7

Views: 6363

Answers (2)

Fred Foo
Fred Foo

Reputation: 363817

gzip.open(zipfile).read() will give you the contents of the file in a single string.

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

will put the contents in a temporary file.

Upvotes: 18

Abhijit
Abhijit

Reputation: 63777

Have you considered using zlib or gzip or tarfile.

Upvotes: 6

Related Questions