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