Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Demo of how to gzip and gunzip a string in Python 3
"""How to gzip a string.
This works for Python 3.2. For 3.1-, look at the original gist (under "Revisions")
import gzip
def gzip_str(string_: str) -> bytes:
return gzip.compress(string_.encode())
def gunzip_bytes_obj(bytes_obj: bytes) -> str:
return gzip.decompress(bytes_obj).decode()
string_ = 'hello there!'
gzipped_bytes = gzip_str(string_)
original_string = gunzip_bytes_obj(gzipped_bytes)
assert string_ == original_string
Copy link

sik0vny commented May 15, 2020


Copy link

danquimby commented Sep 8, 2020


Copy link

paulistoan commented Oct 2, 2020

Thanks! Seems you can also use gzip.decompress() with a bytes object directly:

Copy link

Garrett-R commented Oct 12, 2020

You're welcome! 😄

@paulistoan, great point, I've updated it now.

Copy link

jack980517 commented May 1, 2021

gzip.compress() exists too since 3.2. This whole gist is now unnecessary, except for 3.0 and 3.1. (Except that gzip.decompress() doesn't exist in 3.0 and 3.1 either so the first commit of this gist is needed there.)

Copy link

Garrett-R commented May 4, 2021

Great point @jack980517, I've updated it to reflect that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment