Python 递归遍历文件夹(递归删除XXX文件夹)慎用

这是一个关于如何使用Python的shutil和os模块批量删除指定路径下名为'CellVideo2'的二级目录的脚本。提供了两种方案,第一种通过遍历目录并删除,第二种采用递归方式查找并删除。脚本在执行前提示需谨慎操作。
摘要由CSDN通过智能技术生成
# 批量删除PM1244中CellVideo2
# 请非常谨慎的使用。
import shutil
import os
# PMRootPath = r'X:/PM210603161151244'
PMRootPath = r'D:/Data/SanChaShenJingTong/fzh-2021-05-18(-05-25)'

方案1 指定了必须是第二级。
# count = 0
# dirList = os.listdir(PMRootPath)
# for n,dnum in enumerate(dirList):
#     # print(dnum)
#     d2 = os.listdir(PMRootPath + '/' + dnum)
#     for m,name in enumerate(d2):
#         if name == "CellVideo2":
#             print(PMRootPath + '/' + dnum+'/'+name)
#             # os.removedirs()
#             # shutil.rmtree(PMRootPath + '/' + dnum+'/'+name)
#             count += 1
# print(count)

方案2  递归
# count = 0
deleted_list = []
for home, dirs, files in os.walk(PMRootPath):
    for filename in files:
        if "CellVideo2" in home and home.endswith("CellVideo2") and not home in deleted_list:
            home = home.replace("\\",'/')
            print(home)
            deleted_list.append(home)
            shutil.rmtree(home)


count = len(deleted_list)
print(count)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值