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

Python中open()函数实现文件压缩和解压缩的方法

发布时间:2024-01-13 20:34:20

在Python中,可以使用gzip模块来实现文件压缩和解压缩操作。gzip模块提供了open()函数来处理gzip文件,可以通过writelines()readlines()方法来读写文件内容。

下面是使用gzip模块进行文件压缩和解压缩的方法及其使用示例:

1. 文件压缩:

import gzip

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

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

在上述示例中,我们定义了compress_file()函数用于文件压缩,其中input_file参数为待压缩的文件路径,output_file参数为压缩后的文件路径。通过将待压缩文件以二进制读取模式打开,再将压缩后的文件以二进制写入模式打开,使用writelines()方法将待压缩文件的内容写入压缩文件。

2. 文件解压缩:

import gzip

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

input_file = 'input.txt.gz'
output_file = 'output.txt'
decompress_file(input_file, output_file)

在上述示例中,我们定义了decompress_file()函数用于文件解压缩,其中input_file参数为待解压缩的文件路径,output_file参数为解压缩后的文件路径。通过将待解压缩文件以二进制读取模式打开,再将解压缩后的文件以二进制写入模式打开,使用writelines()方法将待解压缩文件的内容写入解压缩文件。

这里需要注意,压缩文件的扩展名通常为.gz,用以区分压缩文件和普通文本文件。