How to check if a directory exists in python ?

April 15, 2020    /    Viewed: 413    /    Comments: 0    /    Edit


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


Card image cap
profile-image
Daidalos

Je développe le présent site avec le framework python Django. Je m'intéresse aussi actuellement dans le cadre de mon travail au machine learning pour plusieurs projets (voir par exemple) et toutes suggestions ou commentaires sont les bienvenus !