windows下递归解压压缩包并查找指定文件的Python脚本

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\\ 下边的文件
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值