Chinaunix首页 | 论坛 | 博客
  • 博客访问: 916813
  • 博文数量: 75
  • 博客积分: 1216
  • 博客等级: 少尉
  • 技术积分: 1998
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-11 16:20
个人简介

优秀是一种习惯

文章分类

全部博文(75)

文章存档

2014年(1)

2013年(29)

2012年(45)

分类: Python/Ruby

2013-01-24 09:56:22

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

 

 

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