如何检查目录是否存在?


当前回答

是,使用os.path.isdir(路径)

其他回答

如:

In [3]: os.path.exists('/d/temp')
Out[3]: True

很可能会在一条os.path.isdir(…)中抛出。

太近了!如果传入当前存在的目录名,os.path.isdir将返回True。如果它不存在或不是目录,则返回False。

是,使用os.path.isdir(路径)

以下代码检查代码中引用的目录是否存在,如果您的工作场所中不存在,则会创建一个:

import os

if not os.path.isdir("directory_name"):
    os.mkdir("directory_name")
#You can also check it get help for you

if not os.path.isdir('mydir'):
    print('new directry has been created')
    os.system('mkdir mydir')