Skip to content

Instantly share code, notes, and snippets.

@dsaiztc
Forked from Garrett-R/gzip_str.py
Created March 13, 2020 16:07
Show Gist options
  • Save dsaiztc/e4e7a51d2ddd0033316b7f8624ec8dc6 to your computer and use it in GitHub Desktop.
Save dsaiztc/e4e7a51d2ddd0033316b7f8624ec8dc6 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