分类: Python/Ruby
2015-05-26 13:33:01
原文地址:python中zlib模块实例应用 作者:闁
python中zlib模块的实例应用。
zlib模块是用来压缩或者解压缩数据,以便保存和传输。它是其他压缩工具的基础。下面是两段代码:
第一个是用来压缩数据并保存到本地磁盘:
#!/usr/bin/python #-*-coding:UTF-8 -*- import zlib import sys compressor = zlib.compressobj(1) filein = raw_input('please input the filename: ') fileout = raw_input('please input the compressed filename: ') try: fdin = open(filein,'r') except IOError: print 'open %s failed!!!',filein sys.exit(1) fdout = open(fileout,'wb') while True: block = fdin.read(64) if not block : break compressed = compressor.compress(block) fdout.write(compressed) remaining = compressor.flush() fdout.write(remaining) print 'compressed: %s' % filein
第二段,是用来解压数据并保存到本地磁盘:
#!/usr/bin/python #-*- coding UTF-8 -*- import zlib import sys filein = raw_input('please input the compressed filename: ') fileout = raw_input('please input the output filename: ') try: fdin = open(filein,'rb') except IOError: print 'open %s failed!!!' % filein sys.exit(1) fdout = open(fileout,'w') decompressor = zlib.decompressobj() while True: block = fdin.read(128) if not block: break to_de = decompressor.unconsumed_tail + block decompressed = decompressor.decompress(to_de) fdout.write(decompressed) remaining = decompressor.flush() fdout.write(remaining) print 'decompressed'
下面是实验实验过程:
[root@localhost tmp]# tar -cf etc.tar /etc tar: Removing leading `/' from member names [root@localhost tmp]# ls etc.tar ipvsadm-1.24 keepalived-1.1.19 zlib_compressobj.py zlib_decompressobj.py [root@localhost tmp]# ./zlib_compressobj.py please input the filename: /tmp/etc.tar please input the compressed filename: /tmp/etc.tar.zlib compressed: /tmp/etc.tar [root@localhost tmp]# du -h etc.tar 19M etc.tar [root@localhost tmp]# du -h etc.tar.zlib 6.6M etc.tar.zlib [root@localhost tmp]# ./zlib_decompressobj.py please input the compressed filename: /tmp/etc.tar.zlib please input the output filename: /tmp/etc.tar1 decompressed [root@localhost tmp]# du -h etc.tar1 19M etc.tar1 [root@localhost tmp]# tar -xf etc.tar1 [root@localhost tmp]# ls etc etc.tar1 ipvsadm-1.24 zlib_compressobj.py etc.tar etc.tar.zlib keepalived-1.1.19 zlib_decompressobj.py [root@localhost tmp]# cd etc [root@localhost etc]# du -sh . 21M . [root@localhost etc]# du -sh /etc 21M /etc [root@localhost etc]#