🌐
Python
docs.python.org › 3 › library › zlib.html
zlib — Compression compatible with gzip
For applications that require data compression, the functions in this module allow compression and decompression, using the zlib library. This is an optional module. If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you).
🌐
Stack Abuse
stackabuse.com › python-zlib-library-tutorial
Python zlib Library Tutorial
July 17, 2023 - The Python zlib library provides a Python interface to the zlib C library, which is a higher-level abstraction for the DEFLATE lossless compression algorithm....
🌐
W3Schools
w3schools.com › python › ref_module_zlib.asp
Python zlib Module
The zlib module provides functions for compressing and decompressing data using the zlib compression library.
🌐
GitHub
github.com › pycompression › python-zlib-ng
GitHub - pycompression/python-zlib-ng: A drop-in replacement for Python's zlib and gzip modules using zlib-ng · GitHub
A drop-in replacement for Python's zlib and gzip modules using zlib-ng - pycompression/python-zlib-ng
Starred by 14 users
Forked by 7 users
Languages   Python 61.5% | C 38.5%
🌐
Python Module of the Week
pymotw.com › 2 › zlib
zlib – Low-level access to GNU zlib compression library - Python Module of the Week
Now available for Python 3! Buy the book! ... The zlib module provides a lower-level interface to many of the functions in the zlib compression library from GNU.
lossless compression library
zlib (/ˈziːlɪb/ or "zeta-lib", /ˈziːtəˌlɪb/) is a data format and a lossless data compression software library created by Jean-Loup Gailly and Mark Adler. The library implements the Deflate algorithm and supports compressing … Wikipedia
Factsheet
zlib (library)
Release 1 May 1995 (1995-05-01)
Factsheet
zlib (library)
Release 1 May 1995 (1995-05-01)
🌐
zlib
zlib.net
zlib Home Site
zlib Python interface (online manual; part of the standard library as of Python 1.5) zlib Tcl interface mkZiplib · zlib Haskell interface · zlib Java interface (see also JAR format) zlib reimplementation in pure Java · (not tested by us, but looks like a good alternative to java.util.zip) Random access for gzip archives, for Java ·
🌐
PyPI
pypi.org › project › zlib-ng
python-zlib-ng
The zlib-ng contributors for making the zlib-ng library. The CPython contributors. Python-zlib-ng mimicks zlibmodule.c and gzip.py from the standard library to make it easier for python users to adopt it.
      » pip install zlib-ng
    
Published   Sep 10, 2025
Version   1.0.0
🌐
Tutorialspoint
tutorialspoint.com › python › zlib_module.htm
The zlib Module - Python
If your application requires data compression, the functions in this module can be used to perform compression and decompression. This module is a Python implementation of zlib library, which is a part of GNU project.
Find elsewhere
🌐
MicroPython
docs.micropython.org › en › latest › library › zlib.html
zlib – zlib compression & decompression — MicroPython latest documentation
The window size allows you to trade-off memory usage for compression level. A larger window size will allow the compressor to reference fragments further back in the input. The output formats are “raw” DEFLATE (no header/footer), zlib, and gzip, where the latter two include a header and ...
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › zlib.html
zlib — Python Standard Library
The functions in this module allow compression and decompression using the zlib library, which is based on GNU zip.
🌐
Javatpoint
javatpoint.com › python-zlib-library
Python zlib Library
Python zlib Library with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, operators, etc.
Top answer
1 of 4
36

According to RFC 1950 , the difference between the "OK" 0x789C and the "bad" 0x78DA is in the FLEVEL bit-field:

  FLEVEL (Compression level)
     These flags are available for use by specific compression
     methods.  The "deflate" method (CM = 8) sets these flags as
     follows:

        0 - compressor used fastest algorithm
        1 - compressor used fast algorithm
        2 - compressor used default algorithm
        3 - compressor used maximum compression, slowest algorithm

     The information in FLEVEL is not needed for decompression; it
     is there to indicate if recompression might be worthwhile.

"OK" uses 2, "bad" uses 3. So that difference in itself is not a problem.

To get any further, you might consider supplying the following information for each of compressing and (attempted) decompressing: what platform, what version of Python, what version of the zlib library, what was the actual code used to call the zlib module. Also supply the full traceback and error message from the failing decompression attempts. Have you tried to decompress the failing files with any other zlib-reading software? With what results? Please clarify what you have to work with: Does "Am I hosed?" mean that you don't have access to the original data? How did it get from a stream to a file? What guarantee do you have that the data was not mangled in transmission?

UPDATE Some observations based on partial clarifications published in your self-answer:

You are using Windows. Windows distinguishes between binary mode and text mode when reading and writing files. When reading in text mode, Python 2.x changes '\r\n' to '\n', and changes '\n' to '\r\n' when writing. This is not a good idea when dealing with non-text data. Worse, when reading in text mode, '\x1a' aka Ctrl-Z is treated as end-of-file.

To compress a file:

# imports and other superstructure left as a exercise
str_object1 = open('my_log_file', 'rb').read()
str_object2 = zlib.compress(str_object1, 9)
f = open('compressed_file', 'wb')
f.write(str_object2)
f.close()

To decompress a file:

str_object1 = open('compressed_file', 'rb').read()
str_object2 = zlib.decompress(str_object1)
f = open('my_recovered_log_file', 'wb')
f.write(str_object2)
f.close()

Aside: Better to use the gzip module which saves you having to think about nasssties like text mode, at the cost of a few bytes for the extra header info.

If you have been using 'rb' and 'wb' in your compression code but not in your decompression code [unlikely?], you are not hosed, you just need to flesh out the above decompression code and go for it.

Note carefully the use of "may", "should", etc in the following untested ideas.

If you have not been using 'rb' and 'wb' in your compression code, the probability that you have hosed yourself is rather high.

If there were any instances of '\x1a' in your original file, any data after the first such is lost -- but in that case it shouldn't fail on decompression (IOW this scenario doesn't match your symptoms).

If a Ctrl-Z was generated by zlib itself, this should cause an early EOF upon attempted decompression, which should of course cause an exception. In this case you may be able to gingerly reverse the process by reading the compressed file in binary mode and then substitute '\r\n' with '\n' [i.e. simulate text mode without the Ctrl-Z -> EOF gimmick]. Decompress the result. Edit Write the result out in TEXT mode. End edit

UPDATE 2 I can reproduce your symptoms -- with ANY level 1 to 9 -- with the following script:

import zlib, sys
fn = sys.argv[1]
level = int(sys.argv[2])
s1 = open(fn).read() # TEXT mode
s2 = zlib.compress(s1, level)
f = open(fn + '-ct', 'w') # TEXT mode
f.write(s2)
f.close()
# try to decompress in text mode
s1 = open(fn + '-ct').read() # TEXT mode
s2 = zlib.decompress(s1) # error -5
f = open(fn + '-dtt', 'w')
f.write(s2)
f.close()

Note: you will need a use a reasonably large text file (I used an 80kb source file) to ensure that the decompression result will contain a '\x1a'.

I can recover with this script:

import zlib, sys
fn = sys.argv[1]
# (1) reverse the text-mode write
# can't use text-mode read as it will stop at Ctrl-Z
s1 = open(fn, 'rb').read() # BINARY mode
s1 = s1.replace('\r\n', '\n')
# (2) reverse the compression
s2 = zlib.decompress(s1)
# (3) reverse the text mode read
f = open(fn + '-fixed', 'w') # TEXT mode
f.write(s2)
f.close()

NOTE: If there is a '\x1a' aka Ctrl-Z byte in the original file, and the file is read in text mode, that byte and all following bytes will NOT be included in the compressed file, and thus can NOT be recovered. For a text file (e.g. source code), this is no loss at all. For a binary file, you are most likely hosed.

Update 3 [following late revelation that there's an encryption/decryption layer involved in the problem]:

The "Error -5" message indicates that the data that you are trying to decompress has been mangled since it was compressed. If it's not caused by using text mode on the files, suspicion obviously(?) falls on your decryption and encryption wrappers. If you want help, you need to divulge the source of those wrappers. In fact what you should try to do is (like I did) put together a small script that reproduces the problem on more than one input file. Secondly (like I did) see whether you can reverse the process under what conditions. If you want help with the second stage, you need to divulge the problem-reproduction script.

2 of 4
4

I was looking for

python -c 'import sys,zlib;sys.stdout.write(zlib.decompress(sys.stdin.read()))'

wrote it myself; based on answers of zlib decompression in python

🌐
GitHub
github.com › micropython › micropython-lib › blob › master › python-stdlib › zlib › zlib.py
micropython-lib/python-stdlib/zlib/zlib.py at master · micropython/micropython-lib
# MicroPython zlib module · # MIT license; Copyright (c) 2023 Jim Mussared · · import io, deflate · · _MAX_WBITS = const(15) ·
Author   micropython
🌐
GeeksforGeeks
geeksforgeeks.org › python › zlib-compresss-in-python
zlib.compress(s) in python - GeeksforGeeks
March 6, 2020 - Example #1 : In this example we can see that by using zlib.compress(s) method, we are able to compress the string in the byte format by using this method. Python3 1=1 ·
🌐
Jon
jon.glass › blog › has-fun-with-zlib
Use Python zlib to recover Zip Files – Half Full of Security
November 25, 2014 - So continuing on with my series of borderline obsessive blog posts about zip files, I would like to highlight another technique that can be used to recover compressed data. Python comes with library called zlib that is designed to handle the compression and decompression of data.
Top answer
1 of 2
2

One of the best options to compress numpy arrays is using np.savez_compressed. This will be nicer but will be slower. I don't think your compression code is correct

Copyimport numpy as np
import zlib
input_arr = np.arange(100)
dtype = input_arr.dtype
compressed_arr = zlib.compress(input_arr, 2)
decompressed_arr = np.fromstring(zlib.decompress(compressed_arr), dtype)

You can also use blosc which has even better performace

2 of 2
0

so, to sum-up, i cannot use something else than zlib for now but :

  • I can totaly compress/decompress a (unique) numpy array and write/read it to/from a file doing as follow :
Copyrow = array[0,:]
with open(outputFile, 'wb') as zFile:
    print(row)
    compressed = zlib.compress(row, compressionLevel)
    zFile.write(compressed)
Copywith open(os.path.join(path, fileName), 'rb') as zFile:
    decompressed = zlib.decompress(zFile.read())
    data = np.frombuffer(decompressed, dtype=np.float))
    print(data)
  • I added np.frombuffer as pointed out by sagarwal (actually np.frombuffer is better than np.fromstring) and print(row) and print(data) gives the same thing. The probleme comes when i add a for loop in the writing process to add several compressed row in the file. thus i have trouble to retrieve each full size compressed row (with a for line in zFile: ...) to decompress them one at a time. Indeed, some element in each compressed row are seen as \n and thus is does not retrieve the real lines (wich gives zlib.error: Error -5 while decompressing data: incomplete or truncated stream)