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!!
To create your own compressed ZIP files, you must open the ZipFile object in write mode by passing 'w' as the second argument. When you pass a path to the write() method of a ZipFile object, Python will compress the file at that path and add it into the ZIP file.
There is a module gzip. Usage:
Example of how to create a compressed GZIP file:
import gzip content = b"Lots of content here" f = gzip.open('/home/joe/file.txt.gz', 'wb') f.write(content) f.close()
Example of how to GZIP compress an existing file:
import gzip f_in = open('/home/joe/file.txt') f_out = gzip.open('/home/joe/file.txt.gz', 'wb') f_out.writelines(f_in) f_out.close() f_in.close()
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:
import gzip with open('/home/joe/file.txt', 'rb') as f_in, gzip.open('/home/joe/file.txt.gz', 'wb') as f_out: f_out.writelines(f_in)
Read the original file in binary (rb
) mode and then use gzip.open
to create the gzip file that you can write to like a normal file using writelines
:
import gzip with open("path/to/file", 'rb') as orig_file: with gzip.open("path/to/file.gz", 'wb') as zipped_file: zipped_file.writelines(orig_file)
Even shorter, you can combine the with
statements on one line:
with open('path/to/file', 'rb') as src, gzip.open('path/to/file.gz', 'wb') as dst: dst.writelines(src)
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