How to get list of subdirectories names

Just use os.path.isdir on the results returned by os.listdir, as in:

def listdirs(path):
    return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]

You can use os.walk() in various ways

(1) to get the relative paths of subdirectories. Note that '.' is the same value you get from os.getcwd()

for i,j,y in os.walk('.'):
    print(i)

(2) to get the full paths of subdirectories

for root, dirs, files in os.walk('path'):
    print(root)

(3) to get a list of subdirectories folder names

dir_list = []
for root, dirs, files in os.walk(path):
    dir_list.extend(dirs)
print(dir_list)

(4) Another way is glob module (see this answer)


I usually check for directories, while assembling a list in one go. Assuming that there is a directory called foo, that I would like to check for sub-directories:

import os
output = [dI for dI in os.listdir('foo') if os.path.isdir(os.path.join('foo',dI))]

That should work :

my_dirs = [d for d in os.listdir('My_directory') if os.path.isdir(os.path.join('My_directory', d))]

Tags:

Python

List