Read list of zlib archives
<p>I have a file that contains many zlib archives in itself.
Structure of the file looks like:</p>

<pre><code>+-------------------------+
|+-----------------------+|
||     CMF+FLG (78DA)    ||
|+-----------------------+|
|+-----------------------+|
||...compressed data 1...||
|+-----------------------+|
|+-----------------------+|
||        ADLER32        ||
|+-----------------------+|
|
|+-----------------------+|
||     CMF+FLG (78DA)    ||
|+-----------------------+|
|+-----------------------+|
||...compressed data 2...||
|+-----------------------+|
|+-----------------------+|
||        ADLER32        ||
|+-----------------------+|
|
|+-----------------------+|
||     CMF+FLG (78DA)    ||
|+-----------------------+|
|+-----------------------+|
||...compressed data 3...||
|+-----------------------+|
|+-----------------------+|
||        ADLER32        ||
|+-----------------------+|
|                         |
|.........................|
|                         |
|+-----------------------+|
||     CMF+FLG (78DA)    ||
|+-----------------------+|
|+-----------------------+|
||...compressed data n...||
|+-----------------------+|
|+-----------------------+|
||        ADLER32        ||
|+-----------------------+|
+-------------------------+
</code></pre>

<p>And I need iterate over all those archive and extract them.
I tried following code but this extracts only first archive from file.</p>

<pre><code>for filename in sys.argv[1:]:
    with open(filename, 'r') as compressed:
        with open(filename + '-decompressed', 'w') as expanded:
            data = zlib.decompress(compressed.read())
            expanded.write(data)
</code></pre>

<p>You should be able to use a series of decompression objects like this:</p>

<pre><code>import zlib

with open(filename, 'rb') as compressed:
    data = compressed.read()
    file_no = 0

    while data:
        d = zlib.decompressobj()
        with open('{}_decompressed.{}'.format(filename, file_no), 'wb') as f:
            f.write(d.decompress(data))
        data = d.unused_data
        file_no += 1
</code></pre>

<p>This will take a single file containing multiple concatenated zlib compressed files and decompress each one to a separate file with <em>"_decompressed.n"</em> appended to the original file name.</p>

<p>The key is to use the decompression object's <code>unused_data</code> attribute to determine whether there remains any uncompressed data in the string.</p>

python file zlib