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

使用Python压缩和解压缩gzip文件

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

Python中可以使用gzip模块来压缩和解压缩gzip文件。gzip模块提供了gzip.open()函数可以直接操作gzip文件,也可以使用gzip.GzipFile类来操作gzip文件。

下面先给出一个使用gzip模块压缩文件的例子:

import gzip

def compress_file(input_path, output_path):
    with open(input_path, 'rb') as f_in, gzip.open(output_path, '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("文件压缩已完成")

以上示例中,首先通过open()函数以二进制模式打开待压缩的文件,然后使用gzip.open()函数以二进制写模式打开压缩后的文件。接着使用writelines()方法直接将待压缩文件的内容写入到压缩文件中。最后关闭文件。

下面给出一个使用gzip模块解压缩gzip文件的例子:

import gzip

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

input_file = 'example.txt.gz'   # 待解压缩的文件路径
output_file = 'example.txt'   # 解压缩后的文件路径

decompress_file(input_file, output_file)
print("文件解压缩已完成")

以上示例中,我们首先通过gzip.open()函数以二进制读模式打开待解压缩的gzip文件,然后使用open()函数以二进制写模式打开解压缩后的文件。接着使用writelines()方法将gzip文件内容写入到解压缩后的文件中。

使用gzip模块还可以通过设置压缩级别来控制压缩的速度和压缩比。默认级别为6,压缩比较高且速度适中。可以通过在gzip.open()或gzip.GzipFile()函数中设置compresslevel参数来指定压缩级别,取值范围为0-9,0表示不压缩,9表示压缩比最高但速度最慢。

例如,指定压缩级别为最高的示例:

import gzip

def compress_file(input_path, output_path):
    with open(input_path, 'rb') as f_in, gzip.open(output_path, 'wb', compresslevel=9) as f_out:
        f_out.writelines(f_in)

input_file = 'example.txt'   # 待压缩的文件路径
output_file = 'example.txt.gz'   # 压缩后的文件路径

compress_file(input_file, output_file)
print("文件压缩已完成")

以上示例中,在gzip.open()函数中传入compresslevel参数设置压缩级别为9,即 别。根据具体需求,可以选择适当的压缩级别。