如何查找Python中是否存在目录
问题内容:
在os
Python的模块中,有一种方法可以查找目录是否存在,例如:
>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False
问题答案:
您正在寻找
os.path.isdir
,或者
os.path.exists
不管它是文件还是目录:
>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False
另外,您可以使用 pathlib
:
>>> from pathlib import Path
>>> Path('new_folder').is_dir()
True
>>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
False