python 模塊zlib 壓縮與解壓


例子1:壓縮與解壓字符串

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'

例子2:壓縮與解壓文件

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

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

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 "<stdin>", line 1, in <module>
OverflowError: size does not fit in an int

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM