The isdir()
function in the path sub-module of the os
module is used to determine if a given path is an existing directory or not.
A directory is a container in computer memory that holds files and other directories in a hierarchical structure.
To use the function, we first need to import it in our program as follows.
from os.path import isdir
copy
isdir(p)
copy
p |
A string representing the path to be checked. |
The function checks whether path p
represents an existing directory. The path can be relative to the working directory or it can be an absolute path.
Note that the input path:
- Can be an existing directory path, the function will return
True
. - Can be an existing path but not a directory ,
False
will be returned. - Can be invalid and non-existent,
False
will be returned
from os.path import isdir paths = ['project/', 'project/tests.py', 'project/images', 'project/images/person.jpg'] for p in paths: print(isdir(p))
copy
Output:
True
False
True
False
In the above example we used the isdir()
function to test whether some pathnames represents existing directories. Of course, the pathnames are only relevant to the computer they were tested on.