How to check if a directory exists in python ?

Example of how to check if a directory exists in python:

Using the os function isdir()

To check if a file (called for example "images") exists, a solution in python is to use the function isdir :

>>> import os
>>> os.path.isdir('images')

that returns a boolean (True or False) is the directory 'images' exists or not. =

To test if the directory is available with the path /users/john/images:

>>> import os
>>> os.path.isdir('/users/john/images')

Function os.path.exists()

Note 1: the function os.path.exists() is used ti check if a path exists but it can be a file or a directory:

>>> import os
>>> os.path.exists('/users/john/photo.png')
>>> os.path.isdir('/users/john/photo.png')
>>> os.path.isfile('/users/john/photo.png')

Note 2: to get a list of files and directories available under '/users/john/' a solution is to use os.listdir():

>>> os.path.listdir('/users/john/')