利用gzip库实现文件压缩与解压缩的Python代码指南
发布时间:2023-12-17 01:28:51
gzip库是Python中用于gzip压缩与解压缩的标准库之一。利用gzip库可以方便地对文件进行压缩和解压缩操作。
下面是一个示例代码,演示了如何使用gzip库对文件进行压缩和解压缩:
import gzip
import shutil
def compress_file(file_path, compressed_file_path):
with open(file_path, 'rb') as f_in:
with gzip.open(compressed_file_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
def decompress_file(compressed_file_path, decompressed_file_path):
with gzip.open(compressed_file_path, 'rb') as f_in:
with open(decompressed_file_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# 压缩文件
file_path = 'example.txt' # 需要压缩的文件路径
compressed_file_path = 'example.txt.gz' # 压缩后的文件路径
compress_file(file_path, compressed_file_path)
# 解压缩文件
compressed_file_path = 'example.txt.gz' # 需要解压缩的文件路径
decompressed_file_path = 'example.txt' # 解压缩后的文件路径
decompress_file(compressed_file_path, decompressed_file_path)
上述代码中,compress_file函数接受两个参数:file_path代表需要压缩的文件路径,compressed_file_path代表压缩后的文件路径。函数首先以二进制模式打开需要压缩的文件,然后使用gzip.open打开压缩后的文件。接下来,我们利用shutil.copyfileobj将需要压缩的文件内容复制到压缩后的文件中,实现文件的压缩操作。
decompress_file函数的逻辑与compress_file类似,只是相反的过程。首先,我们使用gzip.open打开需要解压缩的文件,然后以二进制模式打开解压缩后的文件。接着,我们同样利用shutil.copyfileobj将需要解压缩的文件内容复制到解压缩后的文件中,实现文件的解压缩操作。
在示例代码中,我们对一个文件进行了压缩和解压缩的操作,example.txt是需要压缩和解压缩的文件。首先,我们对文件进行了压缩操作,并将压缩后的文件保存为example.txt.gz。接着,我们又对压缩后的文件进行了解压缩操作,并将解压缩后的文件保存为example.txt。
以上就是利用gzip库进行文件压缩与解压缩的Python代码指南,希望对你有所帮助。
