python zlib_【python】使用zlib进行压缩解压

A:如何使用zlib模块来进行压缩解压了?

Q:

1.使用zlib.compress可以压缩字符串。使用zlib.decompress可以解压字符串。

压缩解压字符串示范代码:import zlibmessage = 'witch which has which witches wrist watch'compressed = zlib.compress(message)decompressed = zlib.decompress(compressed)print 'original:', repr(message)print 'compressed:', repr(compressed)print 'decompressed:', repr(decompressed) 输出original: 'witch which has which witches wrist watch'compressed: 'x\x9c+\xcf,I\xceP(\xcf\xc8\x04\x92\x19\x89\xc5PV9H4\x15\xc8+\xca,.Q(O\x04\xf2\x00D?\x0f\x89'decompressed: 'witch which has which witches wrist watch'

2.使用zlib.compressobj和zlib.decompressobj比较适合用于对文件进行压缩解压。

以下定义的两个函数可以做为使用zlib.compressobj和zlib.decompressobj对文件进行压缩解压的例子: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())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值