这个代码可以批量解压带密码的压缩包,同时可以选择解压出指定格式的文件。
不过用python解压的速度比不上bandizip,差距巨大。原因不知。
源代码
import time
import zipfile # 用于对zip压缩包的操作
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)]
# 读写文件
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))
# 批量解压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)
if __name__ == ‘__main__‘:
workplace = "D:\Documents\计算机类书籍\处理区\work"
save2path = ‘D:\Documents\计算机类书籍\处理区\works‘
suffix = ‘pdf‘
pwd = b‘123‘
un_zip(workplace, save2path,suffix,pwd)
原文:https://www.cnblogs.com/FlourishingTree/p/15140440.html