How do I gzip compress a string in Python?
gzip.GzipFile
exists, but that's for file objects - what about with plain strings?
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.
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.
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'
The easiest way is the zlib
encoding:
compressed_value = s.encode("zlib")
Then you decompress it with:
plain_string_again = compressed_value.decode("zlib")
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