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

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')

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

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/89217723