gzip a file in Python gzip a file in Python python python

gzip a file in Python


There is a module gzip. Usage:

Example of how to create a compressed GZIP file:

import gzipcontent = 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 gzipf_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 gzipwith 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 gzipwith 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)


Try this:

check_call(['gzip', fullFilePath])

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.