python bz2模塊


bz2模塊提供了使用bzip2算法壓縮和解壓縮數據一套完整的接口。

bz2模塊包括:

 用於讀寫壓縮文件的open()函數BZ2File

 用於一次性壓縮和解壓縮的compress() 和 decompress() 函數

 用於增量壓縮和解壓的 BZ2Compressor 和 BZ2Decompressor 

文件壓縮和解壓

bz2.open(filename, mode='r', compresslevel=9, encoding=None, errors=None, newline=None)

以二進制或文本模式打開 bzip2 壓縮文件,返回一個文件對象。

import bz2

file = bz2.open('xy.bz2', 'r')
for line in file:
    print(line)

class bz2.BZ2File(filename, mode='r', buffering=None, compresslevel=9)

用二進制模式打開 bzip2 壓縮文件

一次性的壓縮和解壓縮

bz2.compress(data)

壓縮文件

bz2.decompress(data)

解壓縮文件

import bz2

def main():
    username = bz2.decompress(un)
    username = username.decode()
    print(username)
    username1 = bz2.compress(username.encode())
    print(username1)

if __name__ == '__main__':
    un = b'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084'
    main()

得到結果:

增量壓縮和解壓縮

 class bz2.BZ2Compressor(compresslevel=9)

  compress(data向壓縮對象提供數據,提供完壓縮數據后,使用fiush()方法以完成壓縮方法

  flush() 結束壓縮進程,返回內部緩沖中剩余的壓縮完成的數據。

 class bz2.BZ2Decompressor

創建一個新的解壓縮器對象。該對象可用於遞增地解壓縮數據。

  decompress(datamax_length=-1)

  解壓縮數據,將未壓縮的數據作為字節返回


免責聲明!

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



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