Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best (most "pythonic") way to temporarily unzip a file

Tags:

python

gzip

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

like image 440
Bi Rico Avatar asked Dec 12 '11 19:12

Bi Rico


People also ask

Can Python unzip files?

In Python, you can zip and unzip files, i.e., compress files into a ZIP file and extract a ZIP file with the zipfile module. Also, you can easily zip a directory (folder) and unzip a ZIP file with make_archive() and unpack_archive() of the shutil module.

How do I unzip multiple zip files in Python?

To unzip a file in Python, use the ZipFile. extractall() method. The extractall() method takes a path, members, pwd as an argument and extracts all the contents. To work on zip files using Python, we will use an inbuilt python module called zipfile.


1 Answers

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.

like image 75
Fred Foo Avatar answered Sep 21 '22 01:09

Fred Foo