《Python 小程序编写系列》(第五部):文件批量压缩工具进阶
·
《Python 小程序编写系列》(第五部):文件批量压缩工具进阶
第四部介绍了基础的批量压缩工具实现,第五部将深入优化功能,增加多格式支持、密码保护、进度显示等高级特性。以下是实现方法和代码示例:
多格式压缩支持
使用zipfile和py7zr库实现ZIP与7Z格式的压缩。需先安装依赖:
pip install zipfile py7zr
import zipfile
import py7zr
from pathlib import Path
def compress_file(file_path, output_path, format='zip', password=None):
if format == 'zip':
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
if password:
zipf.setpassword(password.encode())
zipf.write(file_path, Path(file_path).name)
elif format == '7z':
with py7zr.SevenZipFile(output_path, 'w', password=password) as szf:
szf.write(file_path, Path(file_path).name)
批量压缩与进度显示
通过tqdm库显示处理进度,支持文件夹递归压缩:
from tqdm import tqdm
import os
def batch_compress(input_dir, output_dir, format='zip'):
files = [f for f in Path(input_dir).rglob('*') if f.is_file()]
with tqdm(total=len(files), desc="Compressing") as pbar:
for file in files:
rel_path = file.relative_to(input_dir)
output_path = Path(output_dir) / f"{rel_path.stem}.{format}"
output_path.parent.mkdir(parents=True, exist_ok=True)
compress_file(file, output_path, format)
pbar.update(1)
密码保护功能
为压缩文件添加AES-256加密(仅ZIP格式支持):
def add_password(output_path, password):
if output_path.suffix == '.zip':
with zipfile.ZipFile(output_path, 'a') as zipf:
zipf.setpassword(password.encode())
异常处理与日志记录
使用logging模块记录操作日志,捕获常见异常:
import logging
logging.basicConfig(filename='compression.log', level=logging.INFO)
try:
batch_compress('/input', '/output', format='7z')
except Exception as e:
logging.error(f"Error: {str(e)}", exc_info=True)
完整调用示例
if __name__ == "__main__":
input_dir = "documents"
output_dir = "archives"
password = "secure123"
batch_compress(input_dir, output_dir, format='zip')
for arc in Path(output_dir).glob('*.zip'):
add_password(arc, password)
功能扩展建议
- 增加分卷压缩功能(通过
split_zipfile库) - 支持RAR格式(需安装
rarfile和UNRAR工具) - 添加GUI界面(如PyQt或Tkinter)
通过上述方法可实现一个生产级的批量压缩工具,满足不同场景下的文件压缩需求。
更多推荐



所有评论(0)