Python-zlib库使用
Table of Contents
1 Python中zlib库的使用
最近需要添加zlib库到项目里面,现学习一下。文档可以参照这里:http://docs.python.org/library/zlib.html
1.1 使用zlib解压缩字符串:
import zlib
message = 'aaaabbbbccccdddd'
compressed = zlib.compress(message)
decompressed = zlib.decompress(compressed)
print 'original:', repr(message)
print 'compressed:', repr(compressed)
print 'decompressed:', repr(decompressed)
1.2 使用zlib解压缩文件
def compress(infile, dst, level=9):
infile = open(infile, 'rb')
dst = open(dst, 'wb')
compress = zlib.compressobj(level)
data = infile.read(1024)
while data:
dst.write(compress.compress(data))
data = infile.read(1024)
dst.write(compress.flush())
def decompress(infile, dst):
infile = open(infile, 'rb')
dst = open(dst, 'wb')
decompress = zlib.decompressobj()
data = infile.read(1024)
while data:
dst.write(decompress.decompress(data))
data = infile.read(1024)
dst.write(decompress.flush())
1.3 总结
1.3.1 zlib又来压缩“数据”。
1.3.2 zlib对文件的操作可以看作是文件的存档。
1.3.3 其它面向对象语言(比如cpp)需要wapper zlib的时候可以参照python的wapper思想。
Date: 2012-04-28 02:13:27 CST
HTML generated by org-mode 6.33x in emacs 23