Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I gzip compress a string in Python?

How do I gzip compress a string in Python?

gzip.GzipFile exists, but that's for file objects - what about with plain strings?

like image 811
Bdfy Avatar asked Dec 14 '11 15:12

Bdfy


People also ask

How do I compress a string to gzip?

With the help of gzip. compress(s) method, we can get compress the bytes of string by using gzip. compress(s) method. Return : Return compressed string.

What does gzip do in Python?

The gzip module provides the GzipFile class, as well as the open() , compress() and decompress() convenience functions. The GzipFile class reads and writes gzip-format files, automatically compressing or decompressing the data so that it looks like an ordinary file object.


2 Answers

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' 
like image 185
NPE Avatar answered Sep 30 '22 01:09

NPE


The easiest way is the zlib encoding:

compressed_value = s.encode("zlib") 

Then you decompress it with:

plain_string_again = compressed_value.decode("zlib") 
like image 39
Sven Marnach Avatar answered Sep 30 '22 01:09

Sven Marnach