How to list only top level directories in Python?

前端 未结 18 1395
既然无缘
既然无缘 2020-12-04 07:51

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

18条回答
  •  失恋的感觉
    2020-12-04 08:50

    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']
    

提交回复
热议问题