python解压缩zip文件, 同时显示进度信息

发布时间 2023-09-17 22:19:57作者: 顺其自然,道法自然
  • 直接上代码:
from tqdm import tqdm
import zipfile

def unzip(zipFile):
    '''把ZIP文件解压到以文件名命名的目录中'''
    # 获得文件名(不含后缀),作为解压缩的目录
    dir_name = os.path.dirname(zipFile) # 获取zip文件所在的目录名
    filename = os.path.basename(zipFile)    # 获取zip文件名, 形如: xxx.zip
    name, ext = os.path.splitext(filename) # 分离文件名和后缀
    target_path = os.path.join(dir_name, name) # 设置解压的目标目录
    with zipfile.ZipFile(zipFile) as zf:
        for member in tqdm(zf.infolist(), desc='Extracting '):
            try: zf.extract(member, target_path)
            except zipfile.error as e: raise Exception(f'20211018_1547: 解压缩出现错误.')

运行效果如下:
image