Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gzip a file in Python

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!!

like image 507
Rinks Avatar asked Nov 16 '11 18:11

Rinks


People also ask

How do I compress a file in Python?

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.


2 Answers

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) 
like image 198
Xaerxess Avatar answered Sep 28 '22 04:09

Xaerxess


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) 
like image 23
Jace Browning Avatar answered Sep 28 '22 03:09

Jace Browning