Python 检查多目录是否存在

Python 检查多目录是否存在,python,python-3.x,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) import os, shutil def remove_dirs(dirs): for

此格式看起来正确,但不起作用?

使用循环比手动检查每条路径更好、更干净

def checkandremoveboth():
    dirpath = "C:\Adialapps\CRMV3', 'C:\Adialapps\CRMV2"
if os.path.exists(dirpath) and os.pathisdir(dirpath):
    shutil.rmtree(dirpath)
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)

“不工作”是什么意思?您看到了什么错误消息或意外行为?此外,您在这里有一个竞争条件。您可以检查路径是否存在,但没有理由不能在检查之后,但在脚本执行
shutil.rmtree
之前,由其他进程删除该路径。最好使用
try
/
块来删除目录并捕获任何错误。您也可以使用
ignore\u errors=true
调用它,以在路径不存在时抑制异常,尽管您可能会隐藏其他错误,例如不正确的权限。您是想保留他不匹配的括号吗?我无法完全理解原始代码的含义,但问题似乎很清楚。
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)