1

I have some data that I need to decode using zlib. After a bunch of google searching, I think python could do the trick.

I am a bit lost on how to make this happen; can anyone set me up on the path?

The data is just encoded text; I know that I need to import zlib in a python file, and decode using it, but I am lost where to start.

I have started with this:

import zlib

f = "012301482103"
data = f
zlib.decompress((data))
print data
2
  • 1
    Your example likely won't work because your string f isn't encoded. Commented Jun 21, 2017 at 11:39
  • stackoverflow.com/questions/2695152/… Commented Jun 21, 2017 at 13:41

1 Answer 1

5

use zlib.decompress. It takes a byte object (Python 3.x), hence you need to read your file in binary mode first ( mode 'rb'), and then pass it to decompress():

import zlib

f = open('your_compressed_file', 'rb')
decompressed_data = zlib.decompress(f.read())

If you're using Python 2.7, reading the file with mode 'r' should be sufficient, as in 2.7 it takes a string as input.

If the data isn't a file, simply do this:

data = '9C 2B C9 57 28 CD 73 CE 2F 4B 0D 52 48 2D 4B 2D AA 54 C8 49 2C'

# for Python 2.7
data = data if isinstance(data, str) else str(data,'utf-8')
zlib.decompress(data)

# for Python 3.x
data = data if isinstance(data, bytes) else data.encode('utf-8')
zlib.decompress(data)

Link to the docs for Python 2.7

Link to the docs for Python 3.6

Sign up to request clarification or add additional context in comments.

4 Comments

Had already tried with that, it gives me this: Traceback (most recent call last): File "code", line 5, in <module> zlib.decompress(data) zlib.error: Error -3 while decompressing data: incorrect header check
that's an indication that your data isn't valid - it may be incomplete. This isn't an issue of the code, tho.
I don't think this is gzip data. I'm trying to decode it too: it's from the puzzle at the bottom of this page mi5.gov.uk/careers/cta
Very late to this, but for others... I received "zlib.error: Error -3 while decompressing data: incorrect header check" In my situation, I was decompressing SAML. I needed to add a parameter -15: inflated_data = zlib.decompress(data, -15)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.