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

# 批量删除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)



posted @ 2021-06-07 17:36  bH1pJ  阅读(77)  评论(0编辑  收藏  举报