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

Python实现:gzip压缩和解压缩代码示例

发布时间:2023-12-11 06:49:45

在Python中,可以使用gzip模块来实现gzip压缩和解压缩的功能。下面是一个简单的示例代码,演示如何使用gzip模块进行压缩和解压缩:

1. 压缩文件:

import gzip

def compress_file(input_path, output_path):
    with open(input_path, 'rb') as input_file, gzip.open(output_path, 'wb') as output_file:
        output_file.writelines(input_file)

compress_file('input.txt', 'compressed.gz')

首先,我们通过打开待压缩的文件和gzip.open()函数创建一个压缩文件对象。然后,我们可以使用write()方法将待压缩文件中的内容一行一行地写入压缩文件。最后,我们需要分别关闭输入和输出文件对象。

2. 解压文件:

import gzip

def decompress_file(input_path, output_path):
    with gzip.open(input_path, 'rb') as input_file, open(output_path, 'wb') as output_file:
        output_file.writelines(input_file)

decompress_file('compressed.gz', 'output.txt')

与压缩文件类似,我们通过打开压缩文件和open()函数创建一个解压文件对象,然后使用write()方法将解压后的内容写入输出文件。同样,需要关闭输入和输出文件对象。

使用示例:

compress_file('input.txt', 'compressed.gz')
decompress_file('compressed.gz', 'output.txt')

以上示例代码将会把名为input.txt的文件压缩成compressed.gz文件,然后再将其解压缩成output.txt文件。

需要注意的是,对于较大的文件,压缩和解压缩过程可能需要一定的时间和资源。此外,gzip模块也提供了其他一些函数和方法,比如gzip.compress()方法可以压缩一个字符串,gzip.decompress()方法可以解压缩一个字符串等。具体的使用方法可以查阅Python官方文档。