python中zlib模組是用來壓縮或解壓縮數據,以便保存和傳輸。它是其他壓縮工具的基礎。下面來一起看看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
問題――處理物件過大異常
>>> 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
以上是詳解python用模組zlib壓縮與解壓縮字串和檔案的方法程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!