Python中如何使用bz2模块进行文件压缩
发布时间:2023-12-19 03:03:24
在Python中,我们可以使用bz2模块来进行文件的压缩和解压。bz2模块提供了BZ2File类,可以用来压缩和解压.bz2文件。
下面是一个使用bz2模块进行文件压缩和解压的示例代码:
1. 压缩文件:
import bz2
def compress_file(input_file, output_file):
with open(input_file, 'rb') as f_in:
with bz2.BZ2File(output_file, 'wb') as f_out:
f_out.writelines(f_in)
print(f'压缩文件 {input_file} 完成')
compress_file('input.txt', 'compressed.bz2')
在上述代码中,我们使用open函数打开待压缩的文件input.txt,读取其内容,并使用BZ2File类创建压缩文件compressed.bz2。然后,我们通过写入writelines方法将待压缩文件的内容写入到压缩文件中。
2. 解压文件:
import bz2
def decompress_file(input_file, output_file):
with bz2.BZ2File(input_file, 'rb') as f_in:
with open(output_file, 'wb') as f_out:
f_out.writelines(f_in)
print(f'解压文件 {input_file} 完成')
decompress_file('compressed.bz2', 'output.txt')
在上述代码中,我们使用BZ2File类打开压缩文件compressed.bz2,读取其内容,并使用open函数创建解压文件output.txt。然后,我们通过写入writelines方法将压缩文件的内容写入到解压文件中。
需要注意的是,BZ2File类在读写文件时,会自动处理压缩和解压的过程,我们不需要手动进行压缩和解压的操作。
希望以上的代码示例能够帮助到你。
