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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With