python zlib模块的二个实例

发布时间:2020-04-14编辑:脚本学堂
本文分享二个python中zlib模块的例子,使用python模块zlib实现文件的压缩与解压缩,有需要的朋友参考下。

python中,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