以下是一个简单的文件压缩程序的实现,使用了Python的gzip模块:
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 = 'test.txt'
compressed_file = 'test.txt.gz'
decompressed_file = 'test_decompressed.txt'
# 压缩文件
compress_file(input_file, compressed_file)
# 解压缩文件
decompress_file(compressed_file, decompressed_file)
在上面的代码中,我们定义了两个函数`compress_file`和`decompress_file`,分别用于压缩和解压缩文件。这两个函数都接受两个参数:输入文件名和输出文件名。
在`compress_file`函数中,我们使用`with`语句打开输入文件和输出文件,并使用`gzip.open`函数创建一个gzip文件对象。然后,我们使用`writelines`方法将输入文件的内容写入输出文件中。最后,我们关闭文件对象。
在`decompress_file`函数中,我们使用`gzip.open`函数打开输入文件,并使用`open`函数创建一个输出文件对象。然后,我们使用`writelines`方法将输入文件的内容写入输出文件中。最后,我们关闭文件对象。
在测试代码中,我们定义了三个文件名:输入文件名`test.txt`,压缩后的文件名`test.txt.gz`,以及解压缩后的文件名`test_decompressed.txt`。我们首先使用`compress_file`函数将输入文件压缩成gzip格式的文件,然后使用`decompress_file`函数将压缩后的文件解压缩成原始的文本文件。
From:oirabbit