I want to be able to list only the directories inside some folder. This means I don\'t want filenames listed, nor do I want additional sub-folders.
Let\'s see if an
Use os.walk with next item function:
next(os.walk('.'))[1]
For Python <=2.5 use:
os.walk('.').next()[1]
os.walk
is a generator and calling next
will get the first result in the form of a 3-tuple (dirpath, dirnames, filenames). Thus the [1]
index returns only the dirnames
from that tuple.
For a list of full path names I prefer this version to the other solutions here:
def listdirs(dir):
return [os.path.join(os.path.join(dir, x)) for x in os.listdir(dir)
if os.path.isdir(os.path.join(dir, x))]
directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]
Using list comprehension,
[a for a in os.listdir() if os.path.isdir(a)]
I think It is the simplest way
Filter the result using os.path.isdir() (and use os.path.join() to get the real path):
>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']
This seems to work too (at least on linux):
import glob, os
glob.glob('*' + os.path.sep)