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

Python中如何使用zlib库对文件进行压缩和解压缩操作

发布时间:2023-12-16 23:05:05

在Python中,可以使用zlib库对文件进行压缩和解压缩操作。zlib是一个用于数据压缩和解压缩的库,它提供了对gzip格式的支持。

下面是一个使用zlib库对文件进行压缩和解压缩的例子:

1. 压缩文件:

import zlib

def compress_file(input_file, output_file):
    with open(input_file, 'rb') as file:
        input_data = file.read()
        output_data = zlib.compress(input_data, level=zlib.Z_BEST_COMPRESSION)
        with open(output_file, 'wb') as output:
            output.write(output_data)

input_file = 'input.txt'
output_file = 'compressed.gz'
compress_file(input_file, output_file)

在上面的例子中,我们首先使用open函数打开要压缩的文件,并读取文件的内容。然后,使用zlib.compress函数对文件内容进行压缩,得到压缩后的数据。最后,我们使用open函数打开压缩文件,并将压缩后的数据写入该文件。

2. 解压缩文件:

import zlib

def decompress_file(input_file, output_file):
    with open(input_file, 'rb') as file:
        input_data = file.read()
        output_data = zlib.decompress(input_data)
        with open(output_file, 'wb') as output:
            output.write(output_data)

input_file = 'compressed.gz'
output_file = 'decompressed.txt'
decompress_file(input_file, output_file)

在上面的例子中,我们首先使用open函数打开要解压缩的文件,并读取文件的内容。然后,使用zlib.decompress函数对文件内容进行解压缩,得到解压缩后的数据。最后,我们使用open函数打开解压缩文件,并将解压缩后的数据写入该文件。

需要注意的是,通过zlib进行压缩和解压缩操作时,压缩文件的扩展名通常为.gz。在上面的例子中,我们将压缩文件的扩展名设为了'.gz',以示区分。

另外,需要注意的是,zlib库只能压缩单个文件。如果需要对多个文件进行压缩和解压缩操作,可以使用tarfile库结合zlib库进行操作。