Quixotic
Quixotic

Reputation: 2464

How do you compress a string, and get a string back using zlib?

I am trying to utilize Zlib for text compression.

For example I have a string T='blah blah blah blah' I need to compress it for this string. I am using S=zlib.compress(T) to compress it. Now what I want is to get the non-binary form of S so that I can decompress T but in a different program.

Thanks!

EDIT: I guess I got a method to solve what I wanted. Here is the method:

import zlib, base64
text = 'STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW STACK OVERFLOW '
code =  base64.b64encode(zlib.compress(text,9))
print code

Which gives:

eNoLDnF09lbwD3MNcvPxD1cIHhxcAE9UKaU=

Now I can copy this code to a different program to get the original variable back:

import zlib, base64
s='eNoLDnF09lbwD3MNcvPxD1cIHhxcAE9UKaU='
data = zlib.decompress(base64.b64decode(s))
print data

Please suggest if you are aware of any other compression method which would give better results that are consistent with the above code.

Upvotes: 25

Views: 38034

Answers (2)

Jonathan Prates
Jonathan Prates

Reputation: 1247

Following the comments from the accepted answer, for python 3 users, according to zlib documentation:

def compress(data, /, level=-1)
    Returns a bytes object containing compressed data.

    data
      Binary data to be compressed.
    level
      Compression level, in 0-9 or -1.
(END)

Meaning the first param must be bytes and note that "T" is a string, not bytes. Simply use .encode() from str type to return a copy of this string encoded to bytes, eg:

T = 'blah blah blah blah'
S = zlib.compress(T.encode())

This explains the error TypeError: a bytes-like object is required, not 'str' and fix it.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

Program 1:

T = 'blah blah blah blah'
S = zlib.compress(T)
with open("temp.zlib", "wb") as myfile:
    myfile.write(S)

This saves the compressed string in a file called temp.zlib so that program 2 can later retrieve and decompress it.

Program 2:

with open("temp.zlib", "rb") as myfile:
    S = myfile.read()
T = zlib.decompress(S)

Upvotes: 15

Related Questions