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

利用Python的compress()函数压缩文本文件

发布时间:2023-12-25 01:51:25

compress()函数是Python中的一个文件压缩函数,用于将指定的文件压缩为gzip格式。下面是一个使用compress()函数压缩文本文件的示例:

import gzip

def compress_file(input_filepath, output_filepath):
    with open(input_filepath, 'rb') as file_in:
        with gzip.open(output_filepath, 'wb') as file_out:
            file_out.writelines(file_in)

input_filepath = 'input.txt'
output_filepath = 'compressed.gzip'
compress_file(input_filepath, output_filepath)

在上面的示例中,compress_file()函数接受两个参数,input_filepath是待压缩的文本文件路径,output_filepath是压缩后的文件路径。函数使用了Python的gzip库,利用open()函数将输入文件以二进制模式打开,在打开的文件上使用gzip.open()函数创建一个gzip压缩文件对象。然后,函数使用file_out.writelines(file_in)将输入文件的内容逐行写入压缩文件。最后,使用with语句确保在处理完文件后关闭相关资源。

在实际应用中,你可以将上面的示例代码保存在一个.py文件中,并将input.txt替换为你想要压缩的文本文件路径,output.gzip替换为压缩文件的保存路径。运行该Python程序后,将生成一个gzip压缩文件。注意,gzip压缩文件的后缀为.gz。

压缩文件后,你可以使用gzip库的解压函数解压文件。例如,可以使用gzip.open()函数打开压缩文件并读取其内容:

import gzip

def decompress_file(input_filepath, output_filepath):
    with gzip.open(input_filepath, 'rb') as file_in:
        with open(output_filepath, 'wb') as file_out:
            for line in file_in:
                file_out.write(line)

compressed_filepath = 'compressed.gzip'
decompressed_filepath = 'decompressed.txt'
decompress_file(compressed_filepath, decompressed_filepath)

在上面的示例中,decompress_file()函数接受两个参数,input_filepath是压缩文件的路径,output_filepath是解压后的文件路径。函数通过gzip.open()函数打开压缩文件,并在打开的文件上进行迭代,将每一行内容写入解压后的文件中。最后,使用with语句确保在处理完文件后关闭相关资源。

你可以将上面的示例代码保存在一个.py文件中,并将compressed.gzip替换为你的压缩文件路径,decompressed.txt替换为解压后文件的保存路径。运行该Python程序后,将生成一个解压后的文本文件。