Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2342484
  • 博文数量: 321
  • 博客积分: 3440
  • 博客等级: 中校
  • 技术积分: 2992
  • 用 户 组: 普通用户
  • 注册时间: 2007-05-24 09:08
个人简介

我就在这里

文章分类

全部博文(321)

文章存档

2015年(9)

2014年(84)

2013年(101)

2012年(25)

2011年(29)

2010年(21)

2009年(6)

2008年(23)

2007年(23)

分类: Python/Ruby

2013-01-27 20:32:48

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]#

阅读(936) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~