python zlib庫

Python-zlib庫使用

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思想。

Author: Luo.ZhiHui<[email protected]>

Date: 2012-04-28 02:13:27 CST

HTML generated by org-mode 6.33x in emacs 23

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章