用python批量解压zip(已解决乱码问题)

2021/8/14 11:35:46

本文主要是介绍用python批量解压zip(已解决乱码问题),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

源代码

import time
import zipfile
import os, re

# zip文件所在的绝对路径,保存的路径,解压指定的类型

def point_file_name(path):
    return [os.path.join(item[0], file_name) for item in os.walk(path) for file_name in item[-1] if
            re.search(r'.zip$', file_name)]


# 批量解压zip压缩包 压缩包所在的绝对路径,压缩包要的路径,指定压缩出来的文件格式(默认全部解压出来),pwd

def un_zip(workplace, save2path, suffix="all",pwd=None):
	# 遇空创
    if not (os.path.exists(save2path)):
        os.mkdir(save2path)

    file_names = point_file_name(workplace)  # 绝对路径文件名列表

    for file_name in file_names: # 遍历循环体
        with zipfile.ZipFile(file=file_name, mode='r') as zf:
            for i,zip_info in enumerate(zf.infolist()):
                old_name = zip_info.filename
                print(i)
                # 不要文件夹
                if zip_info.file_size > 0:
                    # 处理乱码
                    new_name = old_name.encode('cp437').decode('utf-8').split('/')[-1]
                    # 拼接文件名
                    new_path = os.path.join(save2path, new_name)

                    if(suffix=="all"):
                        readAndwrite(old_name,new_path,zf)

                    elif(new_name.split('.')[-1] == suffix):
                        readAndwrite(old_name,new_path,zf)

def readAndwrite(old_name,new_path,zf):
    with open(file=new_path, mode='wb') as f:
        # zf.read 是读取压缩包里的文件内容
        read_start = time.time()
        bit = zf.read(old_name, pwd=pwd)
        read_end = time.time()
        f.write(bit)
        write_end = time.time()
        # 时间计算
        read_time = read_end-read_start
        write_time = write_end-read_end
        all_time = read_time+write_time

        print(new_path)
        print("解压完成,读用时:"+str(read_time)+",写用时:"+str(write_time)+",总用时:"+str(all_time))

if __name__ == '__main__':
    workplace = "D:\Documents\计算机类书籍\处理区\work"
    save2path = 'D:\Documents\计算机类书籍\处理区\works'
    suffix = 'pdf'
    pwd = b'123'
    un_zip(workplace, save2path,suffix,pwd)


这篇关于用python批量解压zip(已解决乱码问题)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程