1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| import bz2 def bz2_demo1(): ''' 对类字节对象进行一次性的压缩和解压 ''' data = b'test'
com_bytes = bz2.compress(data) print("压缩后的数据: ", com_bytes) decom_bytes = bz2.decompress(com_bytes) print("解压后的数据: ", decom_bytes)
def bz2_demo2(): ''' 对类字节对象进行增量的压缩和解压 ''' data = [b'test', b'apple'] com_bz2 = bz2.BZ2Compressor() com_bytes = com_bz2.compress(b'') for d in data: com_bytes += com_bz2.compress(d) com_bytes += com_bz2.flush() print("增量压缩: ", com_bytes)
decom_bz2 = bz2.BZ2Decompressor() decom_bytes = decom_bz2.decompress(com_bytes) print("增量解压: ", decom_bytes)
def bz2_demo3(): ''' 对文件对象的压缩与解压 ''' import shutil with open('org_file.txt', 'rb') as read, bz2.open('org_file.txt.gz', 'wb') as write: shutil.copyfileobj(read, write) with bz2.open('org_file.txt.gz', 'rb') as read, open('decom_file.txt', 'wb') as write: shutil.copyfileobj(read, write)
bz2_demo1() bz2_demo2() bz2_demo3()
|