If you want to produce a complete gzip-compatible binary string, with the header etc, you could use gzip.GzipFile together with StringIO:
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import StringIO # Python 3.x
import gzip
out = StringIO()
with gzip.GzipFile(fileobj=out, mode="w") as f:
f.write("This is mike number one, isn't this a lot of fun?")
out.getvalue()
# returns '\x1f\x8b\x08\x00\xbd\xbe\xe8N\x02\xff\x0b\xc9\xc8,V\x00\xa2\xdc\xcc\xecT\x85\xbc\xd2\xdc\xa4\xd4"\x85\xfc\xbcT\x1d\xa0X\x9ez\x89B\tH:Q!\'\xbfD!?M!\xad4\xcf\x1e\x00w\xd4\xea\xf41\x00\x00\x00'
Answer from NPE on Stack OverflowIf you want to produce a complete gzip-compatible binary string, with the header etc, you could use gzip.GzipFile together with StringIO:
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import StringIO # Python 3.x
import gzip
out = StringIO()
with gzip.GzipFile(fileobj=out, mode="w") as f:
f.write("This is mike number one, isn't this a lot of fun?")
out.getvalue()
# returns '\x1f\x8b\x08\x00\xbd\xbe\xe8N\x02\xff\x0b\xc9\xc8,V\x00\xa2\xdc\xcc\xecT\x85\xbc\xd2\xdc\xa4\xd4"\x85\xfc\xbcT\x1d\xa0X\x9ez\x89B\tH:Q!\'\xbfD!?M!\xad4\xcf\x1e\x00w\xd4\xea\xf41\x00\x00\x00'
The easiest way is the zlib encoding:
compressed_value = s.encode("zlib")
Then you decompress it with:
plain_string_again = compressed_value.decode("zlib")
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)