How to list only top level directories in Python?

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

    FWIW, the os.walk approach is almost 10x faster than the list comprehension and filter approaches:

    In [30]: %timeit [d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]
    1.23 ms ± 97.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [31]: %timeit list(filter(os.path.isdir, os.listdir(os.getcwd())))
    1.13 ms ± 13.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [32]: %timeit next(os.walk(os.getcwd()))[1]
    132 µs ± 9.34 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    
    0 讨论(0)
  • 2020-12-04 08:40

    Just to add that using os.listdir() does not "take a lot of processing vs very simple os.walk().next()[1]". This is because os.walk() uses os.listdir() internally. In fact if you test them together:

    >>>> import timeit
    >>>> timeit.timeit("os.walk('.').next()[1]", "import os", number=10000)
    1.1215229034423828
    >>>> timeit.timeit("[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]", "import os", number=10000)
    1.0592019557952881
    

    The filtering of os.listdir() is very slightly faster.

    0 讨论(0)
  • 2020-12-04 08:40
    scanDir = "abc"
    directories = [d for d in os.listdir(scanDir) if os.path.isdir(os.path.join(os.path.abspath(scanDir), d))]
    
    0 讨论(0)
  • 2020-12-04 08:42

    being a newbie here i can't yet directly comment but here is a small correction i'd like to add to the following part of ΤΖΩΤΖΙΟΥ's answer :

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

    for those still on python < 2.4: the inner construct needs to be a list instead of a tuple and therefore should read like this:

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

    otherwise one gets a syntax error.

    0 讨论(0)
  • 2020-12-04 08:42
    [x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]
    
    0 讨论(0)
  • 2020-12-04 08:42

    Like so?

    >>>> [path for path in os.listdir(os.getcwd()) if os.path.isdir(path)]
    
    0 讨论(0)
提交回复
热议问题