Getting a list of all subdirectories in the curren

2018-12-31 19:53发布

Is there a way to return a list of all the subdirectories in the current directory in Python?

I know you can do this with files, but I need to get the list of directories instead.

21条回答
查无此人
2楼-- · 2018-12-31 20:31

You can get the list of subdirectories (and files) in Python 2.7 using os.listdir(path)

import os
os.listdir(path)  # list of subdirectories and files
查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 20:34

Much nicer than the above, because you don't need several os.path.join() and you will get the full path directly (if you wish), you can do this in Python 3.5+

subfolders = [f.path for f in os.scandir(folder) if f.is_dir() ]    

This will give the complete path to the subdirectory. If you only want the name of the subdirectory use f.name instead of f.path

https://docs.python.org/3/library/os.html#os.scandir

查看更多
荒废的爱情
4楼-- · 2018-12-31 20:34

use a filter function os.path.isdir over os.listdir() something like this filter(os.path.isdir,[os.path.join(os.path.abspath('PATH'),p) for p in os.listdir('PATH/')])

查看更多
登录 后发表回答