在Python中使用bz2模块对压缩文件进行分片读取和写入的方法
发布时间:2024-01-14 05:11:55
在Python中,可以使用bz2模块对压缩文件进行分片读取和写入。bz2模块是Python标准库中的一个模块,提供了对bzip2压缩算法的支持。
下面是一个使用bz2模块对压缩文件进行分片读取和写入的例子:
import bz2
def compress_file(input_file, output_file):
CHUNK_SIZE = 1024 * 1024 # 每次读取1MB数据
with open(input_file, 'rb') as input:
with bz2.open(output_file, 'wb') as output:
while True:
chunk = input.read(CHUNK_SIZE)
if not chunk:
break
output.write(chunk)
def decompress_file(input_file, output_file):
CHUNK_SIZE = 1024 * 1024 # 每次读取1MB数据
with bz2.open(input_file, 'rb') as input:
with open(output_file, 'wb') as output:
while True:
chunk = input.read(CHUNK_SIZE)
if not chunk:
break
output.write(chunk)
# 示例:压缩文件
input_file = 'example.txt' # 待压缩的文件
compressed_file = 'compressed_file.bz2' # 压缩后的文件
compress_file(input_file, compressed_file)
print(f'文件{input_file}已压缩为{compressed_file}。')
# 示例:解压缩文件
decompressed_file = 'decompressed_file.txt' # 解压缩后的文件
decompress_file(compressed_file, decompressed_file)
print(f'文件{compressed_file}已解压缩为{decompressed_file}。')
上述代码中,定义了两个函数compress_file和decompress_file,分别用于压缩和解压缩文件。这两个函数通过open函数打开输入文件和输出文件,然后使用bz2.open函数创建用于读取和写入的bz2.BZ2File对象。
在compress_file函数中,使用一个循环不断从输入文件中读取数据,每次读取1MB的数据,然后将读取到的数据写入到输出文件中。直到输入文件的所有数据都被读取和写入完毕。
在decompress_file函数中,使用同样的方式从压缩文件中读取数据,然后将读取到的数据写入到解压缩后的文件中。
可以根据实际需求调整CHUNK_SIZE的值来控制每次读取和写入的数据大小。
以上是使用bz2模块对压缩文件进行分片读取和写入的方法及使用例子。
