Guido van Rossum | 9a4da08 | 1999-03-12 19:07:59 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
Guido van Rossum | 5416a0d | 1997-05-28 16:13:21 +0000 | [diff] [blame] | 2 | |
| 3 | import zlib, sys |
| 4 | if len(sys.argv)>1: filename=sys.argv[1] |
| 5 | else: filename='zlibdemo.py' |
| 6 | print 'Reading', filename |
| 7 | f=open(filename, 'r') # Get the data to compress |
| 8 | s=f.read() |
| 9 | f.close() |
| 10 | |
| 11 | # First, we'll compress the string in one step |
| 12 | comptext=zlib.compress(s, 1) |
| 13 | decomp=zlib.decompress(comptext) |
| 14 | |
| 15 | print '1-step compression: (level 1)' |
| 16 | print ' Original:', len(s), 'Compressed:', len(comptext), |
| 17 | print 'Uncompressed:', len(decomp) |
| 18 | |
| 19 | # Now, let's compress the string in stages; set chunk to work in smaller steps |
| 20 | |
| 21 | chunk=256 |
| 22 | compressor=zlib.compressobj(9) |
| 23 | decompressor=zlib.decompressobj() |
| 24 | comptext=decomp='' |
| 25 | for i in range(0, len(s), chunk): |
| 26 | comptext=comptext+compressor.compress(s[i:i+chunk]) |
| 27 | comptext=comptext+compressor.flush() # Don't forget to call flush()!! |
| 28 | |
| 29 | for i in range(0, len(comptext), chunk): |
| 30 | decomp=decomp+decompressor.decompress(comptext[i:i+chunk]) |
| 31 | decomp=decomp+decompressor.flush() |
| 32 | |
| 33 | print 'Progressive compression (level 9):' |
| 34 | print ' Original:', len(s), 'Compressed:', len(comptext), |
| 35 | print 'Uncompressed:', len(decomp) |
| 36 | |