Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1521368
  • 博文数量: 399
  • 博客积分: 8508
  • 博客等级: 中将
  • 技术积分: 5302
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-14 09:28
个人简介

能力强的人善于解决问题,有智慧的人善于绕过问题。 区别很微妙,小心谨慎做后者。

文章分类

全部博文(399)

文章存档

2018年(3)

2017年(1)

2016年(1)

2015年(69)

2013年(14)

2012年(17)

2011年(12)

2010年(189)

2009年(93)

分类: Python/Ruby

2013-01-29 00:22:55

原文地址: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]# 

 

 

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