3 # Takes an optional filename, defaulting to this file itself.
4 # Reads the file and compresses the content using level 1 and level 9
5 # compression, printing a summary of the results.
11 filename
= sys
.argv
[1]
13 filename
= sys
.argv
[0]
14 print 'Reading', filename
16 f
= open(filename
, 'rb') # Get the data to compress
20 # First, we'll compress the string in one step
21 comptext
= zlib
.compress(s
, 1)
22 decomp
= zlib
.decompress(comptext
)
24 print '1-step compression: (level 1)'
25 print ' Original:', len(s
), 'Compressed:', len(comptext
),
26 print 'Uncompressed:', len(decomp
)
28 # Now, let's compress the string in stages; set chunk to work in smaller steps
31 compressor
= zlib
.compressobj(9)
32 decompressor
= zlib
.decompressobj()
33 comptext
= decomp
= ''
34 for i
in range(0, len(s
), chunk
):
35 comptext
= comptext
+compressor
.compress(s
[i
:i
+chunk
])
36 # Don't forget to call flush()!!
37 comptext
= comptext
+ compressor
.flush()
39 for i
in range(0, len(comptext
), chunk
):
40 decomp
= decomp
+ decompressor
.decompress(comptext
[i
:i
+chunk
])
41 decomp
=decomp
+decompressor
.flush()
43 print 'Progressive compression (level 9):'
44 print ' Original:', len(s
), 'Compressed:', len(comptext
),
45 print 'Uncompressed:', len(decomp
)
47 if __name__
== '__main__':