I want to gzip a file in Python. I am trying to use the subprocss.check_call(), but it keeps failing with the error 'OSError: [Errno 2] No such file or directory'. Is there a problem with what I am trying here? Is there a better way to gzip a file than using subprocess.check_call?
from subprocess import check_call
def gZipFile(fullFilePath)
check_call('gzip ' + fullFilePath)
Thanks!!
Try this:
Depending on what you're doing with the data of these files, Skirmantas's link to http://docs.python.org/library/gzip.html may also be helpful. Note the examples near the bottom of the page. If you aren't needing to access the data, or don't have the data already in your Python code, executing gzip may be the cleanest way to do it so you don't have to handle the data in Python.
Use the gzip module:
Your error:
OSError: [Errno 2] No such file or directory'
is telling you that the filefullFilePath
does not exist. If you still need to go that route, please make sure that file exists on your system and you are using an absolute path not relative.There is a module gzip. Usage:
Example of how to create a compressed GZIP file:
Example of how to GZIP compress an existing file:
EDIT:
Jace Browning's answer using
with
in Python >= 2.7 is obviously more terse and readable, so my second snippet would (and should) look like:the documentation on this is actually insanely straightforward
Example of how to read a compressed file:
Example of how to create a compressed GZIP file:
Example of how to GZIP compress an existing file:
https://docs.python.org/2/library/gzip.html
That's the whole documentation . . .
In Python 2.7 format:
Even shorter (Tested on python 2.7.6)