windows下递归解压压缩包并查找指定文件的Python脚本
代码如下
下面有注释说明怎么修改`.
# -*- coding: utf-8 -*-
# @Time : 20210420
# @Author : hujiazhuo
import shutil
import zipfile
import os
# 把所有 .RAR 替换成 你要的后缀
recursive_unzip_file = []
def recursive_unzip(path, zfile):
file_path = path + os.sep + zfile
# 给解压后的文件生成文件名相同的文件夹
des_dir = path + os.sep + zfile[:zfile.index('.RAR')]
srcfile = zipfile.ZipFile(file_path)
for file_name in srcfile.namelist():
if file_name.endswith('.RAR'):
temp_del_file = os.path.join(des_dir, file_name)
if temp_del_file not in recursive_unzip_file:
recursive_unzip_file.append(temp_del_file)
srcfile.extract(file_name, des_dir)
if file_name.endswith('.RAR'):
temp_del_file = os.path.join(des_dir, zfile)
if temp_del_file not in recursive_unzip_file:
recursive_unzip_file.append(temp_del_file)
# if zipfile.is_zipfile(filename):
path = des_dir
zfile = file_name
recursive_unzip(path, zfile)
def del_file(file_path):
"""
删除指定路径下的所有文件和文件夹
:param file_path: 路径
:return:
"""
for del_file_path in file_path:
if os.path.isfile(del_file_path):
os.remove(del_file_path)
elif os.path.isdir(del_file_path):
shutil.rmtree(del_file_path)
file_list = list() #将查找出的文件存放在列表中
def find_file(file_path):
if os.path.isfile( file_path):#判断是否为文件,此为基例,递归终止点
file_list.append(file_path)
else: #如果是目录,执行下边的程序
for file_ls in os.listdir( file_path):#循环目录中的文件
find_file(os.path.join( file_path,file_ls))#再次判断目录中的文件,实现递归,函数调用函数本身
return file_list #退出最终的文件列表
if __name__ == '__main__':
#递归解压
path = r'.\\' #修改成你要操作的目录
zfile = r'123.RAR' #修改成你要解压的文件
recursive_unzip_file.append(os.path.join(path, zfile))
recursive_unzip(path, zfile)
print(recursive_unzip_file)
print(len(recursive_unzip_file))
del_file(recursive_unzip_file)
#递归查找
print(find_file(".\\123\\")) #查找 e:/.\\123\\ 下边的文件