python 模組zlib 壓縮與解壓

2022-02-18 23:28:52 字數 1939 閱讀 8450

import

zlib

message = '

abcd1234

'compressed =zlib.compress(message)

decompressed =zlib.decompress(compressed)

print

'original:

', repr(message)

print

'compressed:

', repr(compressed)

print

'decompressed:

', repr(decompressed)

結果

original: '

abcd1234

'compressed:

'x\x9ckljn1426\x01\x00\x0b\xf8\x02u

'decompressed:

'abcd1234

'

import

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())

defdecompress(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())

if__name__ == "

__main__":

compress(

'in.txt

', '

out.txt')

decompress(

'out.txt

', '

out_decompress.txt

')

結果生成檔案

out_decompress.txt  out.txt

zlib.compress用於壓縮流資料。引數string指定了要壓縮的資料流,引數level指定了壓縮的級別,它的取值範圍是1到9。壓縮速度與壓縮率成反比,1表示壓縮速度最快,而壓縮率最低,而9則表示壓縮速度最慢但壓縮率最高

>>>import zlib

>>> a = '

123'

>>> b =zlib.compress(a)

>>>b

'x\x9c342\x06\x00\x01-\x00\x97

'>>> a = '

a' * 1024 * 1024 * 1024 * 10

>>> b =zlib.compress(a)

traceback (most recent call last):

file

"", line 1, in

overflowerror: size does not fit

in an int

zlib(非流壓縮)

wget tar xvzf zlib 1.2.3.tar.gz cd zlib 1.2.3.tar.gz configure make sudo make install安裝好之後,就可以用了 zlibmgr.h 檔案 ifndef zlibmgr define zlibmgr define max...

qt 呼叫zlib壓縮與解壓縮功能

zlib是一種免費且通用的壓縮庫,由於zlib壓縮效果比lzw好,而且解壓縮速度快,更重要的是商業軟體中使用zlib不需要繳納版權費,所以很多遊戲都使用zlib壓縮資源檔案。zlib聯合使用lz77演算法和huffman哈夫曼樹來實現資料壓縮和資料解壓。zlib原始碼 void mainwindow...

Zlib檔案壓縮和解壓

zlib檔案壓縮和解壓 開源 http www.zlib.net zlib使用手冊 http www.zlib.net manual.html zlib wince版 http www.tenik.co.jp adachi wince 在這裡,你可以檢視基於各種作業系統平台的壓縮與解縮 實現。以下是...