检查是否存在多个目录

时间:2018-12-06 01:36:57

标签: python python-3.x

def checkandremoveboth():
    dirpath = "C:\Adialapps\CRMV3', 'C:\Adialapps\CRMV2"
if os.path.exists(dirpath) and os.pathisdir(dirpath):
    shutil.rmtree(dirpath)

这种格式看起来正确但不起作用?

2 个答案:

答案 0 :(得分:2)

import os, shutil

def remove_dirs(dirs):
    for dir in dirs:
        shutil.rmtree(dir, ignore_errors=True) # https://docs.python.org/3/library/shutil.html#shutil.rmtree

dirs = ["C:\Adialapps\CRMV3', 'C:\Adialapps\CRMV2"]
remove_dirs(dirs)

答案 1 :(得分:2)

一种更好的循环方式,而不是手动检查每个路径。

import os

def check_and_remove(pathsList):
    for path in pathsList:
        if os.path.exists(path) and os.path.isdir(path):
            shutil.rmtree(dir,ignore_errors=True)
            print("Deleted")
        else:
            print(path, " directory not found")


dirs_to_delete = [
    'C:\Adialapps\CRMV3',
    'C:\Adialapps\CRMV2'
]

check_and_remove(dirs_to_delete)