views:

2840

answers:

7

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 example helps. In the current directory we have:

>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
 'Tools', 'w9xpopen.exe']

However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:

>>> for root, dirnames, filenames in os.walk('.'):
...     print dirnames
...     break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']

However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.

+7  A: 

directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]

Mark Roddy
This can be shortened to filter (os.path.isdir, os.listdir (os.getcwd ())
John Millikin
I think the list comprehension is more readable.
nosklo
Does anyone have any information on whether filter or a list comprehension is faster? Otherwise its just a subjective argument. This of course assumes there's 10 million directories in the cwd and performance is an issue.
Mark Roddy
A: 

Like so?

>>> [path for path in os.listdir(os.getcwd()) if os.path.isdir(path)]

Just Some Guy
A: 
[x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]
Moe
+11  A: 

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']
Thomas Wouters
+1  A: 

Filter the list using os.path.isdir to detect directories.

>>> filter (os.path.isdir, os.listdir(os.getcwd()))`
Colin Jensen
+3  A: 

Note that, instead of doing os.listdir(os.getcwd()), it's preferable to do os.listdir(os.path.curdir). One less function call, and it's as portable.

So, to complete the answer, to get a list of directories in a folder:

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

If you prefer full pathnames, then use this function:

def listdirs(folder):
    return [
        d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
        if os.path.isdir(d)
    ]
ΤΖΩΤΖΙΟΥ
+4  A: 
os.walk('.').next()[1]
fivebells