python用模塊zlib壓縮與解壓字符串和文件的方法
python中zlib模塊是用來(lái)壓縮或者解壓縮數(shù)據(jù),以便保存和傳輸。它是其他壓縮工具的基礎(chǔ)。下面來(lái)一起看看python用模塊zlib壓縮與解壓字符串和文件的方法。話不多說(shuō),直接來(lái)看示例代碼。
例子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)
結(jié)果
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')
結(jié)果
生成文件
out_decompress.txt out.txt
問(wèn)題——處理對(duì)象過(guò)大異常
>>> 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
總結(jié)
以上就是關(guān)于python模塊zlib壓縮與解壓的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家學(xué)習(xí)或者使用python能有一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
???????Python?入門學(xué)習(xí)之函數(shù)式編程
這篇文章主要介紹了???????Python?入門學(xué)習(xí)之函數(shù)式編程,?Python?中的函數(shù)式編程技術(shù)進(jìn)行了簡(jiǎn)單的入門介紹,下文詳細(xì)內(nèi)容需要的小伙伴可以參考一下2022-05-05入門tensorflow教程之TensorBoard可視化模型訓(xùn)練
在本篇文章中,主要介紹 了TensorBoard 的基礎(chǔ)知識(shí),并了解如何可視化訓(xùn)練模型中的一些基本信息,希望對(duì)大家的TensorBoard可視化模型訓(xùn)練有所幫助2021-08-08python?如何實(shí)現(xiàn)跳過(guò)異常繼續(xù)執(zhí)行
這篇文章主要介紹了python?如何實(shí)現(xiàn)跳過(guò)異常繼續(xù)執(zhí)行,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07python實(shí)現(xiàn)在cmd窗口顯示彩色文字
今天小編就為大家分享一篇python實(shí)現(xiàn)在cmd窗口顯示彩色文字,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06python按修改時(shí)間順序排列文件的實(shí)例代碼
這篇文章主要介紹了python按修改時(shí)間順序排列文件的實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-07-07