To display all directories in the current path in Python, you can use the os
module. This module provides a lot of functionality to work with files, directories and paths.
main.py241 chars12 lines
In the first step, we get the current working directory using the os.getcwd()
function. In the second step, we use list comprehension to get a list of all directories in the current path by filtering out all non-directory files using the os.path.isdir
function. Finally, we print all directories using a for loop.
Note that the os.listdir()
function returns not only directories but all files and directories. To filter out only directories, we check each element with os.path.isdir()
. We use os.path.join()
to combine the path with the directory name to check if a particular element is a directory or not.
gistlibby LogSnag