How to list only top level directories in Python?

前端 未结 18 1401
既然无缘
既然无缘 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)
    

提交回复
热议问题