第八章:数据压缩与归档-bz2:bzip2压缩-写压缩文件

本文介绍如何使用Python的BZ2File模块进行bzip2压缩文件的读写操作,包括不同压缩级别的效果对比及如何使用writelines方法写入字符串序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

8.3.4 写压缩文件
可以用BZ2File读写bzip2压缩文件,并使用通常的方法读写数据。

import bz2
import io
import os

data = 'Contents of the example file go here.\n'

with bz2.BZ2File('example.bz2','wb') as output:
    with io.TextIOWrapper(output,encoding='utf-8') as enc:
        enc.write(data)

os.system('file example.bz2')

为了把数据写入一个压缩文件,需要用模式’wb’打开文件。这个例子用io模块的一个TextIOWrapper来包装BZ2File,将Unicode文件编码为适合压缩的字节。
运行结果:
在这里插入图片描述
通过传入一个compresslevel参数,可以使用不同的压缩量。合法值为1-9(包括1到9)。值越小便会得到越快的处理,压缩也越少。较大的值会得到较慢的处理,但压缩更多 (直到某个上限)。

import bz2
import io
import os

data = open('lorem.txt','r',encoding='utf-8').read() * 1024
print('Input contains {} butes'.format(
    len(data.encode('utf-8'))))
for i in range(1,10):
    filename = 'compress-level-{}.bz2'.format(i)
    with bz2.BZ2File(filename,'wb',compresslevel=i) as output:
        with io.TextIOWrapper(output,encoding='utf-8') as enc:
            enc.write(data)
    os.system('cksum {}'.format(filename))

脚本输出中,中间一列数字显示了所生成文件的大小(字节数)。对于这个输入数据,更高的压缩值并不一定得到更少的存储空间。不过对于其他输入,结果可能有所不同。
运行结果:

Input contains 1234944 butes

在这里插入图片描述
BZ2File实例还包括一个writelines()方法,可以用来写一个字符串序列。

import bz2
import io
import itertools
import os

data = 'The same line,over and over.\n'

with bz2.BZ2File('lines.bz2','wb') as output:
    with io.TextIOWrapper(output,encoding='utf-8') as enc:
        enc.writelines(itertools.repeat(data,10))

os.system('bzcat lines.bz2')

与写入常规文件类似,这些行要以一个换行符结尾。
运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值