How to check if a directory exists in python ?

How to check if a directory exists in python ?

Daidalos April 15, 2020


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')
True
>>> os.path.isdir('/users/john/photo.png')
False
>>> os.path.isfile('/users/john/photo.png')
True

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/')

References

Links Site
isfile docs.python.org
isdir docs.python.org
how to check if a file is a directory or regular file in python? [duplicate] stackoverflow
How do I list all files of a directory? stackoverflow
Getting file size in Python? [duplicate] stackoverflow
Python Check If File or Directory Exists guru99.com
Python: Check if a File or Directory Exists stackabuse