display all directories in the current path in python

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.py
import os

# get current directory
path = os.getcwd()

# get list of directories in the current path
directories = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]

# print directories
for d in directories:
    print(d)
241 chars
12 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.

related categories

gistlibby LogSnag