How to list only top level directories in Python?

前端 未结 18 1231
既然无缘
既然无缘 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:45

    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.

    0 讨论(0)
  • 2020-12-04 08:45

    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))]
    
    0 讨论(0)
  • 2020-12-04 08:49
    directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]
    
    0 讨论(0)
  • 2020-12-04 08:49

    Using list comprehension,

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

    I think It is the simplest way

    0 讨论(0)
  • 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']
    
    0 讨论(0)
  • 2020-12-04 08:50

    This seems to work too (at least on linux):

    import glob, os
    glob.glob('*' + os.path.sep)
    
    0 讨论(0)
提交回复
热议问题