熱線電話:13121318867

登錄
首頁精彩閱讀python用模塊zlib壓縮與解壓字符串和文件的方法
python用模塊zlib壓縮與解壓字符串和文件的方法
2018-04-06
收藏

python用模塊zlib壓縮與解壓字符串和文件的方法

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壓縮與解壓的全部內容,希望本文的內容對大家學習或者使用python能有一定的幫助

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢