How to list only top level directories in Python?
os.walk
Use os.walk
with next
item function:
next(os.walk('.'))[1]
For Python <=2.5 use:
os.walk('.').next()[1]
How this works
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.
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']