To get the list of subdirectories under the given path, we need to interact with the OS filesystem. Python made it easy by providing the “os” module. It provides the functionality to interact with the operating systems.

Just import the “os” module and with that, we can access the file system and get the list of files under the directory using the scandir.

After getting the files, we need to check if the file is a directory or not. If it is a directory then add it to the list else ignore it.

import os

path = r"<Path>"

# Remove "if f.is_dir()" if you want to list all files.
list_subdir_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]

scandir() is faster when compared to other methods such as pathlib, listdir, walk etc.

Categorized in:

Tagged in: