Python中使用gzip实现文件写入压缩与解压缩的完整示例代码
发布时间:2023-12-28 12:32:57
以下是Python中使用gzip实现文件写入压缩与解压缩的完整示例代码:
## 文件写入压缩
import gzip
def compress_file(file_path):
with open(file_path, 'rb') as f_in:
compressed_file_path = file_path + '.gz'
with gzip.open(compressed_file_path, 'wb') as f_out:
f_out.writelines(f_in)
return compressed_file_path
file_path = 'example.txt'
compressed_file_path = compress_file(file_path)
print(f"Compressed file: {compressed_file_path}")
以上代码中,首先通过open()函数以读取二进制模式打开待压缩的文件,然后通过gzip.open()函数以写入二进制模式打开压缩后的文件。使用writelines()方法将待压缩文件的内容写入压缩文件。最后返回压缩后的文件路径。
## 文件解压缩
import gzip
def decompress_file(compressed_file_path):
decompressed_file_path = compressed_file_path[:-3] # Remove .gz extension
with gzip.open(compressed_file_path, 'rb') as f_in:
with open(decompressed_file_path, 'wb') as f_out:
f_out.write(f_in.read())
return decompressed_file_path
compressed_file_path = 'example.txt.gz'
decompressed_file_path = decompress_file(compressed_file_path)
print(f"Decompressed file: {decompressed_file_path}")
以上代码中,首先通过gzip.open()函数以读取二进制模式打开压缩文件,然后通过open()函数以写入二进制模式打开解压缩后的文件。使用read()方法从压缩文件中读取内容,并使用write()方法将解压缩后的内容写入文件。最后返回解压缩后的文件路径。
下面是一个完整的使用示例:
import gzip
def compress_file(file_path):
with open(file_path, 'rb') as f_in:
compressed_file_path = file_path + '.gz'
with gzip.open(compressed_file_path, 'wb') as f_out:
f_out.writelines(f_in)
return compressed_file_path
def decompress_file(compressed_file_path):
decompressed_file_path = compressed_file_path[:-3] # Remove .gz extension
with gzip.open(compressed_file_path, 'rb') as f_in:
with open(decompressed_file_path, 'wb') as f_out:
f_out.write(f_in.read())
return decompressed_file_path
# 压缩示例
file_path = 'example.txt'
compressed_file_path = compress_file(file_path)
print(f"Compressed file: {compressed_file_path}")
# 解压缩示例
compressed_file_path = 'example.txt.gz'
decompressed_file_path = decompress_file(compressed_file_path)
print(f"Decompressed file: {decompressed_file_path}")
希望以上示例能够帮助到你!
