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?

Andersson
  • 51,635
  • 17
  • 77
  • 129
  • 2
    If you use [`os.walk`](https://docs.python.org/2/library/os.html#os.walk) it gives you directories and files separately. – jonrsharpe Jun 25 '15 at 11:55

5 Answers5

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))]
jhoepken
  • 1,842
  • 3
  • 17
  • 24
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)

blackraven
  • 5,284
  • 7
  • 19
  • 45
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
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))]
Wei Jiang
  • 55
  • 5
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
3

That should work :

my_dirs = [d for d in os.listdir('My_directory') if os.path.isdir(os.path.join('My_directory', d))]
coincoin
  • 4,595
  • 3
  • 23
  • 47
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)
user1016274
  • 4,071
  • 1
  • 23
  • 19