How to find if directory exists in Python

David542 picture David542 · Jan 19, 2012 · Viewed 1.1M times · Source

In the os module in Python, is there a way to find if a directory exists, something like:

>>> os.direxists(os.path.join(os.getcwd()), 'new_folder')) # in pseudocode
True/False

Answer

phihag picture phihag · Jan 19, 2012

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