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

我知道您可以对文件执行此操作,但我需要获得目录列表。


当前回答

Python 3.4在标准库中引入了pathlib模块,它提供了一种面向对象的方法来处理文件系统路径:

from pathlib import Path

p = Path('./')

# All subdirectories in the current directory, not recursive.
[f for f in p.iterdir() if f.is_dir()]

要递归地列出所有子目录,路径通配符可以与**模式一起使用。

# This will also include the current directory '.'
list(p.glob('**'))

请注意,一个*作为glob模式将非递归地包括文件和目录。为了只获取目录,可以在后面追加一个/,但这只在直接使用glob库时有效,而不是通过pathlib使用glob时:

import glob

# These three lines return both files and directories
list(p.glob('*'))
list(p.glob('*/'))
glob.glob('*')

# Whereas this returns only directories
glob.glob('*/')

因此Path('./').glob('**')匹配与glob相同的路径。一团(“* * /”,递归= True)。

Pathlib也可以通过PyPi上的pathlib2模块在Python 2.7中使用。

其他回答

这个答案似乎并不存在。

directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]

由于我在使用Python 3.4和Windows UNC路径时偶然发现了这个问题,下面是这个环境的一个变体:

from pathlib import WindowsPath

def SubDirPath (d):
    return [f for f in d.iterdir() if f.is_dir()]

subdirs = SubDirPath(WindowsPath(r'\\file01.acme.local\home$'))
print(subdirs)

Pathlib是Python 3.4中的新功能,它使得在不同操作系统下使用路径更加容易: https://docs.python.org/3.4/library/pathlib.html

使用过滤函数os.path.isdir over os.listdir() 类似这样的过滤器(os.path.isdir,[os.path.join(os.path.abspath('PATH'),p) for p in os.listdir('PATH/')])

你可以用glob。glob

from glob import glob
glob("/path/to/directory/*/", recursive = True)

不要忘记*后面的/。

以Eli Bendersky的解决方案为基础,使用以下示例:

import os
test_directory = <your_directory>
for child in os.listdir(test_directory):
    test_path = os.path.join(test_directory, child)
    if os.path.isdir(test_path):
        print test_path
        # Do stuff to the directory "test_path"

>是要遍历的目录的路径。