有没有办法在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中使用。

其他回答

这应该可以工作,因为它还创建了一个目录树;

import os
import pathlib

def tree(directory):
    print(f'+ {directory}')
    print("There are " + str(len(os.listdir(os.getcwd()))) + \
    " folders in this directory;")
    for path in sorted(directory.glob('*')):
        depth = len(path.relative_to(directory).parts)
        spacer = '    ' * depth
        print(f'{spacer}+ {path.name}')

这应该列出使用pathlib库的文件夹中的所有目录。path.relative_to(目录)。Parts获取相对于当前工作目录的元素。

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中使用。

在ipython中复制粘贴友好:

import os
d='.'
folders = list(filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)))

从打印(文件夹)输出:

['folderA', 'folderB']
import os

d = '.'
[os.path.join(d, o) for o in os.listdir(d) 
                    if os.path.isdir(os.path.join(d,o))]

我最近也遇到过类似的问题,我发现python 3.6的最佳答案(用户havlock添加的)是使用os.scandir。由于似乎没有使用它的解决方案,所以我将添加自己的解决方案。首先是一种非递归解决方案,它只列出根目录下的子目录。

def get_dirlist(rootdir):

    dirlist = []

    with os.scandir(rootdir) as rit:
        for entry in rit:
            if not entry.name.startswith('.') and entry.is_dir():
                dirlist.append(entry.path)

    dirlist.sort() # Optional, in case you want sorted directory names
    return dirlist

递归的版本是这样的:

def get_dirlist(rootdir):

    dirlist = []

    with os.scandir(rootdir) as rit:
        for entry in rit:
            if not entry.name.startswith('.') and entry.is_dir():
                dirlist.append(entry.path)
                dirlist += get_dirlist(entry.path)

    dirlist.sort() # Optional, in case you want sorted directory names
    return dirlist

记住这一项。Path使用子目录的绝对路径。如果您只需要文件夹名称,您可以使用entry.name代替。参考os。DirEntry获取关于条目对象的其他详细信息。