获取当前目录中所有子目录的列表 [英] Getting a list of all subdirectories in the current directory

查看:254
本文介绍了获取当前目录中所有子目录的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法返回Python中当前目录中所有子目录的列表?



我知道你可以用文件来做这个,但是我需要

解决方案

你是否意味着立即的子目录,或者是树下的每个目录?



无论哪种方式,您都可以使用 os.walk 执行此操作:

  os.walk(目录)

将为每个子目录产生一个元组。在3元组中的第一个条目是一个目录名,所以

  [x [0] for o in os.walk目录)] 

应该给你所有的目录。



请注意,元组中的第二个条目是条目的第一个位置的子目录的列表,所以您可以使用这个列表,但不太可能节省很多。



但是,您可以使用它来为您提供直接的子目录:

  next(os [1] 

或者看到已经发布的其他解决方案,使用< a href =http://docs.python.org/library/os.html#os.listdir =nofollow noreferrer> os.listdir os.path.isdir ,包括那些在如何得到所有的Python中的直接子目录


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.

解决方案

Do you mean immediate subdirectories, or every directory right down the tree?

Either way, you could use os.walk to do this:

os.walk(directory)

will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so

[x[0] for x in os.walk(directory)]

should give you all of the directories.

Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much.

However, you could use it just to give you the immediate child directories:

next(os.walk('.'))[1]

Or see the other solutions already posted, using os.listdir and os.path.isdir, including those at "How to get all of the immediate subdirectories in Python".

这篇关于获取当前目录中所有子目录的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆