How to find if directory exists in Python
You're looking for os.path.isdir
, or os.path.exists
if you don't care whether it's a file or a directory:
>>> import os>>> os.path.isdir('new_folder')True>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))False
Alternatively, you can use pathlib
:
>>> from pathlib import Path >>> Path('new_folder').is_dir() True >>> (Path.cwd() / 'new_folder' / 'file.txt').exists() False
Python 3.4 introduced the pathlib
module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir()
and exists()
methods of a Path
object can be used to answer the question:
In [1]: from pathlib import PathIn [2]: p = Path('/usr')In [3]: p.exists()Out[3]: TrueIn [4]: p.is_dir()Out[4]: True
Paths (and strings) can be joined together with the /
operator:
In [5]: q = p / 'bin' / 'vim'In [6]: qOut[6]: PosixPath('/usr/bin/vim') In [7]: q.exists()Out[7]: TrueIn [8]: q.is_dir()Out[8]: False
Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.