Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead.
Is there a way to return a list of all the subdirectories in the current directory in Python?
I know you can do this with files, but I need to get the list of directories instead.
Here are a couple of simple functions based on @Blair Conrad's example -
If you need a recursive solution that will find all the subdirectories in the subdirectories, use walk as proposed before.
If you only need the current directory's child directories, combine
os.listdir
withos.path.isdir
Building upon Eli Bendersky's solution, use the following example:
where
<your_directory>
is the path to the directory you want to traverse.Python 3.4 introduced the
pathlib
module into the standard library, which provides an object oriented approach to handle filesystem paths:Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.
Since I stumbled upon this problem using Python 3.4 and Windows UNC paths, here's a variant for this environment:
Pathlib is new in Python 3.4 and makes working with paths under different OSes much easier: https://docs.python.org/3.4/library/pathlib.html
I've had a similar question recently, and I found out that the best answer for python 3.6 (as user havlock added) is to use
os.scandir
. Since it seems there is no solution using it, I'll add my own. First, a non-recursive solution that lists only the subdirectories directly under the root directory.The recursive version would look like this:
keep in mind that
entry.path
wields the absolute path to the subdirectory. In case you only need the folder name, you can useentry.name
instead. Refer to os.DirEntry for additional details about theentry
object.