Categories
Python Answers

How to get a list of all subdirectories in the current directory with Python?

Spread the love

Sometimes, we want to get a list of all subdirectories in the current directory with Python.

In this article, we’ll look at how to get a list of all subdirectories in the current directory with Python.

How to get a list of all subdirectories in the current directory with Python?

To get a list of all subdirectories in the current directory with Python, we can use the os.walk method.

For instance, we write:

import os

directory = '/'
dirs = [x[0] for x in os.walk(directory)]
print(dirs)

We call os.walk with the directory path to return an iterator with the tuples containing the directory path strings.

Then we can get them get the directory path string from each tuple with x[0].

Therefore, dirs is something like ['./', './.upm'].

Conclusion

To get a list of all subdirectories in the current directory with Python, we can use the os.walk method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *