To list directories in Python, import the os
module and call the os.listdir()
function on a specific directory.
π‘ Info: The os
module provides a way to interact with the operating system. It is part of the standard library within Python 3.
You can use the os.path()
module to check if each item in the list returned by listdir()
is a directory.
Below is an example of how to do this:
import os items = os.listdir('.') for item in items: if os.path.isdir(item): print(item)

This will print
the names of all directories in the current directory. If you want to list directories in a different directory, you can pass the path to that directory to the listdir()
function instead of the current directory dot '.'
.
For example, to list directories in the Linux home directory, you can do the following:
import os items = os.listdir('/home') for item in items: if os.path.isdir(item): print(item)

Traverse Directory Tree with os.walk()
The os.path.isdir()
function checks whether a given path is a directory or not.
If you want to list directories in a nested directory structure, you can use the os.walk()
function, which generates the file names in a directory tree by walking the tree either top-down or bottom-up.
Hereβs an example of using os.walk()
to list directories in a nested directory structure.
import os # List dirs in current and all subdirectories for root, dirs, files in os.walk('.'): for dir in dirs: print(os.path.join(root, dir))

This will print the names of all directories in the current directory and all its subdirectories.
π Recommended Tutorial: How to List All Files of a Python Directory?