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
Shaido
  • 27,497
  • 23
  • 70
  • 73
Dware
  • 49
  • 1
  • 1
  • 9

1 Answers1

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

deepbrook
  • 2,523
  • 4
  • 28
  • 49
  • Hi, thanks for this; but it is not a file I have. Should I just save it as a text file and put text.txt ? – Dware Jun 21 '17 at 12:01
  • in that case, simply pass your data to `decompress()` if it's a `string` - if it's a `bytes` object, you will have to convert according to your python version. – deepbrook Jun 21 '17 at 13:38
  • Hi thanks for update for python 3.6. So the text I have, do i replace the data in brackets with it? Can you post your full example with the data? Here it is: 9C 2B C9 57 28 CD 73 CE 2F 4B 0D 52 48 2D 4B 2D AA 54 C8 49 2C – Dware Jun 21 '17 at 13:53
  • updated my answer – deepbrook Jun 21 '17 at 14:03
  • Had already tried with that, it gives me this: Traceback (most recent call last): File "code", line 5, in zlib.decompress(data) zlib.error: Error -3 while decompressing data: incorrect header check – Dware Jun 21 '17 at 14:08
  • that's an indication that your data isn't valid - it may be incomplete. This isn't an issue of the code, tho. – deepbrook Jun 21 '17 at 14:56
  • 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 https://www.mi5.gov.uk/careers/cta – Beetle Jan 28 '18 at 22:47