简体   繁体   English

如何列出目录中的所有目录

[英]How do I list all the directories in a directory

I would like to know if there's a quick 1 line of code to list all the directories in a directory.我想知道是否有快速的 1 行代码来列出目录中的所有目录。 It's similar to this question: How do I list all files of a directory?它类似于这个问题: 如何列出目录的所有文件? , but with folders instead of files. ,但使用文件夹而不是文件。

Here is a recipe for just the first level:这是第一级的食谱:

dname = '/tmp'
[os.path.join(dname, d) for d in next(os.walk(dname))[1]]

and a recursive one:和一个递归的:

dname = '/tmp'
[os.path.join(root, d) for root, dirs, _ in os.walk(dname) for d in dirs]

(after import os , obviously) (显然在import os之后)


Note that on filesystems that support symbolic links, any links to directories will not be included here, only actual directories.请注意,在支持符号链接的文件系统上,任何指向目录的链接不会包含在此处,仅包含实际目录。

Using os.listdir to list all the files and folders and os.path.isdir as the condition:使用 os.listdir 列出所有文件和文件夹,并使用 os.path.isdir 作为条件:

import os   
cpath = r'C:\Program Files (x86)'
onlyfolders = [f for f in os.listdir(cpath) if os.path.isdir(os.path.join(cpath, f))]

Import os导入操作系统

#use os.walk() #使用 os.walk()

Example:例子:

For folder, sub, file in os.walk(path): Print(folder).对于os.walk(路径)中的文件夹,子文件:打印(文件夹)。 #returns parent folder Print (sub). #returns 父文件夹打印(子)。 #returns sub_folder Print (file) # returns files #returns sub_folder Print (file) # 返回文件

[ i[0] for i in os.walk('/tmp')]
  1. here '/tmp' is the directory path for which all directories are listed这里 '/tmp' 是列出所有目录的目录路径
  2. you need to import os你需要导入操作系统

This works because i[0] gives all the root paths as it will walk through them so we don't need to do join or anything.这是有效的,因为 i[0] 给出了所有的根路径,因为它会遍历它们,所以我们不需要做连接或任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM