Python3 数据压缩和归档
import os
import tarfile
import zipfile
from io import BytesIO
from tempfile import TemporaryFile
def compress_file(file_path, compression_format):
"""
将指定文件根据压缩格式进行压缩。
:param file_path: 文件路径
:param compression_format: 压缩格式,支持 'zip' 或 'tar.gz'
:return: 压缩后的文件对象和压缩格式
"""
if compression_format not in ['zip', 'tar.gz']:
raise ValueError("Unsupported compression format")
with open(file_path, 'rb') as file:
compressed_file = BytesIO()
if compression_format == 'zip':
with zipfile.ZipFile(compressed_file, 'w', zipfile.ZIP_DEFLATED) as zip_file:
zip_file.writestr(os.path.basename(file_path), file.read())
elif compression_format == 'tar.gz':
with tarfile.open(fileobj=compressed_file, mode='w:gz') as tar_file:
tar_file.add(file_path, arcname=os.path.basename(file_path))
compressed_file.seek(0)
return compressed_file, compression_format
def decompress_file(compressed_file, compression_format):
"""
将指定的压缩文件解压至临时文件中。
:param compressed_file: 压缩文件对象
:param compression_format: 压缩格式
:return: 解压后的临时文件对象
"""
compressed_file.seek(0)
temp_file = TemporaryFile()
if compression_format == 'zip':
with zipfile.ZipFile(compressed_file) as zip_file:
with temp_file:
temp_file.write(zip_file.read(zip_file.namelist()[0]))
elif compression_format == 'tar.gz':
with tarfile.open(fileobj=compressed_file) as tar_file:
with temp_file:
temp_file.write(tar_file.extractfile(tar_file.getmembers()[0]).read())
temp_file.seek(0)
return temp_file
# 示例使用
compressed_file, compression_format = compress_file('example.txt', 'zip')
decompressed_file = decompress_file(compressed_file, compression_format)
print(decompressed_file.read().decode())
compressed_file.close()
decompressed_file.close()
这段代码展示了如何使用Python进行文件的压缩和解压。其中compress_file
函数接受文件路径和压缩格式,然后压缩文件。decompress_file
函数接受压缩文件对象和压缩格式,将文件解压至临时文件中。最后,我们提供了使用这些功能的示例。
评论已关闭