Skip to content

Instantly share code, notes, and snippets.

@Garrett-R
Last active March 12, 2022 10:17
Show Gist options
  • Save Garrett-R/dc6f08fc1eab63f94d2cbb89cb61c33d to your computer and use it in GitHub Desktop.
Save Garrett-R/dc6f08fc1eab63f94d2cbb89cb61c33d to your computer and use it in GitHub Desktop.
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
@danquimby
Copy link

Thanks!

@paulistoan
Copy link

paulistoan commented Oct 2, 2020

Thanks! Seems you can also use gzip.decompress() with a bytes object directly: https://docs.python.org/3/library/gzip.html#gzip.decompress.

@Garrett-R
Copy link
Author

You're welcome! 😄

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

@jack980517
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.)

@Garrett-R
Copy link
Author

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