List Subdirectories of a Directory in Python

List Subdirectories of a Directory in Python

This tutorial explains how to list all subdirectories of a given directory using Python.

We will use the glob module in Python for this purpose. We will begin with importing the glob module.

List Subdirectories of a Directory in Python

Import glob:

from glob import glob

The above code will import the glob module for us. We will now have to decide on a directory for which we want to list the subdirectories.

In our case, we are selecting the Users directory in our system.

We will use the glob() function in the glob module to perform the task. The glob() function takes the directory’s path as an input and sets the recursive parameter as true to go through all the subdirectories.

We will write the below code to perform the operation.

print(glob("C:/Users/*/", recursive = True))

The trailing * and / are essential while using the above function; the function returns a list containing all the subdirectories.

['C:/Users\\All Users\\', 'C:/Users\\Analysis_of_RNNs_and_different_ML_&_DL_classifiers_on_Speech_based_Emotion_Recognition_System_using_linear_and_non-linear_features\\', 'C:/Users\\Default\\', 'C:/Users\\Default User\\', 'C:/Users\\Public\\', 'C:/Users\\Shivesh\\']

As we can see above, we got a list of all the subdirectories of our passed directory.

Therefore, we can obtain a list of subdirectories of a given directory in Python using the above technique.

Preet Sanghavi avatar Preet Sanghavi avatar

Preet writes his thoughts about programming in a simplified manner to help others learn better. With thorough research, his articles offer descriptive and easy to understand solutions.

LinkedIn GitHub

Related Article - Python Directory

  • Python Get Home Directory
  • List All Files in Directory and Subdirectories in Python
  • Fix the No Such File in Directory Error in Python
  • Get Directory From Path in Python
  • Execute a Command on Each File in a Folder in Python