14

There is a directory that contains folders as well as files of different formats.

import os 
my_list = os.listdir('My_directory')

will return full content of files and folders names. I can use, for example, endswith('.txt') method to select just text files names, but how to get list of just folders names?

1
  • 2
    If you use os.walk it gives you directories and files separately.
    – jonrsharpe
    Jun 25, 2015 at 11:55

5 Answers 5

34

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))]
8

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)

5

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))]
0
3

That should work :

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

os.walk already splits files and folders up into different lists, and works recursively:

for root,dirs,_ in os.walk('.'):
    for d in dirs:
        print os.path.join(root,d)

Not the answer you're looking for? Browse other questions tagged or ask your own question.