1

How can I get the list of folders in current working directory in Python?
I need only the folders, not files or sub-folders.

Alex L
  • 8,748
  • 5
  • 49
  • 75
  • http://stackoverflow.com/questions/141291/how-to-list-only-top-level-directories-in-python – ndpu Feb 11 '13 at 09:33

2 Answers2

3

Simple list comprehension:

[fn for fn in os.listdir(u'.') if os.path.isdir(fn)]
nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

Thanks to @ATOzTOA
You can use os.listdir and os.path.isfile like here:

import os

path = 'whatever your path is'

for item in os.listdir(path):
    if not os.path.isfile(os.path.join(path, item)):
        print "Folder: ",item
    else:
        print "File: ",item

Now you know what are folders and what are files.
Since you don't want files, you can simply store the folders (path or name) in a list
For that, Do this:

import os

path = 'whatever your path is'
folders = [] # list that will contain folders (path+name)

for item in os.listdir(path):
    if not os.path.isfile(os.path.join(path, item)):
        folders.append(os.path.join(path, item)) #  os.path.join(path, item) is your folder path
Community
  • 1
  • 1
pradyunsg
  • 18,287
  • 11
  • 43
  • 96