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

使用Python的_IO模块实现文件的压缩与解压缩的方法与实例

发布时间:2024-01-06 05:04:23

在Python中,可以使用_io模块中的GzipFile类来实现文件的压缩与解压缩。GzipFile类通过使用gzip算法对文件进行压缩和解压缩。

下面是一个简单的使用例子,展示了如何使用GzipFile类来压缩和解压缩文件:

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)

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 = 'example.txt'
output_file = 'example.txt.gz'
compress_file(input_file, output_file)
print(f'压缩完成:{output_file}')

# 解压缩文件
input_file = 'example.txt.gz'
output_file = 'example_decompressed.txt'
decompress_file(input_file, output_file)
print(f'解压缩完成:{output_file}')

在上面的例子中,首先定义了两个函数:compress_filedecompress_file,分别用于压缩和解压缩文件。这两个函数都接受输入文件和输出文件的路径作为参数。

在函数compress_file中,我们使用open函数来打开输入文件并以二进制读取模式打开,然后使用gzip.open函数以二进制写入模式打开输出文件。接着,我们使用writelines方法将输入文件的内容写入到输出文件中,这样就完成了文件的压缩。

在函数decompress_file中,我们使用gzip.open函数以二进制读取模式打开输入文件,并使用open函数以二进制写入模式打开输出文件。然后,我们再次使用writelines方法将输入文件的内容写入到输出文件中,从而完成了文件的解压缩。

在例子的最后,我们分别调用了compress_filedecompress_file函数,来演示如何使用GzipFile类来压缩和解压缩文件。这个例子会将名为example.txt的文本文件压缩为example.txt.gz,然后再将压缩后的文件解压缩为example_decompressed.txt

以上就是使用Python的_io模块中的GzipFile类实现文件压缩和解压缩的方法和一个简单的使用例子。