【Python】解压文件/ZIP等 并实时计算解压进度

 

import zipfile
def read_zip(zip_file_path: str, unpack_path: str, ws_msg: WebSocketMsg):
    """
    解压ZIP文件
    @param zip_file_path: ZIP文件路径(ex. E:\aaa\a.zip)
    @param unpack_path: 解压文件输出路径(ex. E:\aaa)
    @param ws_msg: 用来放实时进度的类(可干掉)
    """

    file_list = zipfile.ZipFile(zip_file_path)
    info = file_list.infolist()

    ''' 1 计算解压后的文件总大小(单位:字节B) '''
    all_size = 0
    for i in info:
        all_size += i.file_size
    # 1.1 字节B转换为兆字节MB (字符串)
    all_size_str = str(int(all_size / 1024 / 1024)) + 'MB'

    ''' 2 当前已解压的文件总大小(单位:字节B) '''
    now_size = 0
    for i in info:
        file_list.extract(i, unpack_path)
        now_size += i.file_size
        # 2.1 字节B转换为兆字节MB (字符串)
        now_size_str = str(int(now_size / 1024 / 1024)) + 'MB'
        ws_msg.msg.append(f'解压进度:{int(now_size / all_size * 100)}% ({now_size_str}/{all_size_str})')
        # print(f'解压进度:{int(now_size / all_size * 100)}% ({now_size_str}/{all_size_str})')
    file_list.close()

 

posted @ 2022-01-08 14:13  淡怀  阅读(1267)  评论(0编辑  收藏  举报