• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2
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.
6
7import zlib, sys
8
9def main():
10    if len(sys.argv) > 1:
11        filename = sys.argv[1]
12    else:
13        filename = sys.argv[0]
14    print 'Reading', filename
15
16    f = open(filename, 'rb')           # Get the data to compress
17    s = f.read()
18    f.close()
19
20    # First, we'll compress the string in one step
21    comptext = zlib.compress(s, 1)
22    decomp = zlib.decompress(comptext)
23
24    print '1-step compression: (level 1)'
25    print '    Original:', len(s), 'Compressed:', len(comptext),
26    print 'Uncompressed:', len(decomp)
27
28    # Now, let's compress the string in stages; set chunk to work in smaller steps
29
30    chunk = 256
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()
38
39    for i in range(0, len(comptext), chunk):
40        decomp = decomp + decompressor.decompress(comptext[i:i+chunk])
41    decomp=decomp+decompressor.flush()
42
43    print 'Progressive compression (level 9):'
44    print '    Original:', len(s), 'Compressed:', len(comptext),
45    print 'Uncompressed:', len(decomp)
46
47if __name__ == '__main__':
48    main()
49