欢迎访问宙启技术站
智能推送

在Python中使用bz2模块实现文件的高效压缩和解压缩

发布时间:2024-01-14 05:06:47

Python的bz2模块是用于实现文件的高效压缩和解压缩的模块。它提供了对BZ2文件格式的支持,该格式使用Burrows-Wheeler变换和霍夫曼编码来实现压缩。

使用bz2模块进行文件压缩和解压缩的过程如下:

1. 压缩文件:将原始文件压缩成BZ2格式的文件。

2. 解压文件:将BZ2格式的文件解压成原始文件。

下面是使用bz2模块进行文件压缩和解压缩的示例代码:

import bz2

# 压缩文件
def compress_file(input_file, output_file):
    with open(input_file, 'rb') as f_in, bz2.open(output_file, 'wb') as f_out:
        f_out.write(f_in.read())

# 解压文件
def decompress_file(input_file, output_file):
    with bz2.open(input_file, 'rb') as f_in, open(output_file, 'wb') as f_out:
        f_out.write(f_in.read())

# 压缩示例
input_file = 'example.txt'
compressed_file = 'example.bz2'
compress_file(input_file, compressed_file)
print('文件已压缩')

# 解压示例
input_file = 'example.bz2'
decompressed_file = 'example_decompressed.txt'
decompress_file(input_file, decompressed_file)
print('文件已解压')

在上面的示例中,compress_file函数用于将指定的输入文件压缩成BZ2格式的输出文件。它使用bz2.open函数以二进制模式打开输出文件,并通过write方法将输入文件的内容写入。

decompress_file函数用于将指定的输入文件解压成原始文件。它使用bz2.open函数以二进制模式打开输入文件,并通过read方法读取压缩文件的内容,并将解压缩的结果写入到指定的输出文件中。

在示例中,我们首先将一个名为example.txt的文件压缩成example.bz2文件,然后再将example.bz2文件解压成example_decompressed.txt文件。压缩和解压缩的结果文件都会存储在当前目录中。

以上就是使用Python的bz2模块进行文件压缩和解压缩的简单示例。通过使用bz2模块,我们可以实现文件的高效压缩和解压缩,并节省存储空间。