您当前的位置: 首页 >  Python

IT之一小佬

暂无认证

  • 4浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

python中zlib库用法详解

IT之一小佬 发布时间:2022-09-01 22:18:13 ,浏览量:4

zlib主要用于压缩与解压缩

  • 字符串:使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。
  • 数据流:压缩:compressobj,解压:decompressobj

示例代码:

import zlib

data = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' \
       'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'
print(len(data))
print(data)

# 压缩
compressed_data = zlib.compress(data.encode())  # 注意:这儿要以字节的形式传入
print(len(compressed_data))
print(compressed_data)

# 解压
new_data = zlib.decompress(compressed_data).decode()
print(len(new_data))
print(new_data)

运行结果:

示例代码2:

import zlib


# 压缩文件或数据
def compress_data(file, zip_file, level=9):
    file = open(file, 'rb')
    zip_file = open(zip_file, 'wb')
    compress = zlib.compressobj(level)
    data = file.read(1024)
    while data:
        zip_file.write(compress.compress(data))
        data = file.read(1024)
    zip_file.write(compress.flush())
    file.close()
    zip_file.close()


# 解压文件或数据
def decompress_data(zip_file, new_file):
    zip_file = open(zip_file, 'rb')
    new_file = open(new_file, 'wb')
    decompress = zlib.decompressobj()
    data = zip_file.read(1024)
    while data:
        new_file.write(decompress.decompress(data))
        data = zip_file.read(1024)
    new_file.write(decompress.flush())
    zip_file.close()
    new_file.close()


if __name__ == '__main__':
    file = 'text.txt'
    zip_file = 'text_zip.txt'
    compress_data(file, zip_file)

    new_file = 'test_new.txt'
    decompress_data(zip_file, new_file)
    print('end!')

运行结果:

注意:compressobj返回一个压缩对象,用来压缩不能一下子读入内存的数据流。 level 从9到-1表示压缩等级,其中1最快但压缩度最小,9最慢但压缩度最大,0不压缩,默认是-1大约相当于与等级6,是一个压缩速度和压缩度适中的level。

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0518s