Skip to content

Instantly share code, notes, and snippets.

@mavjs
Forked from Garrett-R/gzip_str.py
Created April 25, 2020 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mavjs/88d659233a840c45c149a6ea68848bd8 to your computer and use it in GitHub Desktop.
Save mavjs/88d659233a840c45c149a6ea68848bd8 to your computer and use it in GitHub Desktop.
Demo of how to gzip and gunzip a string in Python 3
import gzip
import io
def gzip_str(string_):
out = io.BytesIO()
with gzip.GzipFile(fileobj=out, mode='w') as fo:
fo.write(string_.encode())
bytes_obj = out.getvalue()
return bytes_obj
def gunzip_bytes_obj(bytes_obj):
in_ = io.BytesIO()
in_.write(bytes_obj)
in_.seek(0)
with gzip.GzipFile(fileobj=in_, mode='rb') as fo:
gunzipped_bytes_obj = fo.read()
return gunzipped_bytes_obj.decode()
string_ = 'hello there!'
gzipped_bytes = gzip_str(string_)
original_string = gunzip_bytes_obj(gzipped_bytes)
assert string_ == original_string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment