Python 如何获取子目录名称列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31049648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get list of subdirectories names
提问by Andersson
There is a directory that contains folders as well as files of different formats.
有一个目录,其中包含文件夹以及不同格式的文件。
import os
my_list = os.listdir('My_directory')
will return full content of files and folders names. I can use, for example, endswith('.txt')
method to select just text files names, but how to get list of just folders names?
将返回文件和文件夹名称的完整内容。例如,我可以使用endswith('.txt')
方法仅选择文本文件名,但如何获取仅文件夹名称的列表?
采纳答案by jhoepken
I usually check for directories, while assembling a list in one go. Assuming that there is a directory called foo
, that I would like to check for sub-directories:
我通常会检查目录,同时一次性组装一个列表。假设有一个名为 的目录foo
,我想检查子目录:
import os
output = [dI for dI in os.listdir('foo') if os.path.isdir(os.path.join('foo',dI))]
回答by Frerich Raabe
Just use os.path.isdir
on the results returned by os.listdir
, as in:
只需os.path.isdir
在 返回的结果上使用os.listdir
,如下所示:
def listdirs(path):
return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
回答by coincoin
That should work :
那应该工作:
my_dirs = [d for d in os.listdir('My_directory') if os.path.isdir(os.path.join('My_directory', d))]
回答by Avinash Raj
You may use os.walk
您可以使用 os.walk
for i,j,y in os.walk('.'):
print(i)
回答by user1016274
os.walk
already splits files and folders up into different lists, and works recursively:
os.walk
已经将文件和文件夹分成不同的列表,并递归地工作:
for root,dirs,_ in os.walk('.'):
for d in dirs:
print os.path.join(root,d)