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

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


当前回答

这个答案似乎并不存在。

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

其他回答

只列出目录

print("\nWe are listing out only the directories in current directory -")
directories_in_curdir = list(filter(os.path.isdir, os.listdir(os.curdir)))
print(directories_in_curdir)

只列出当前目录中的文件

files = list(filter(os.path.isfile, os.listdir(os.curdir)))
print("\nThe following are the list of all files in the current directory -")
print(files)

你可以用glob。glob

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

不要忘记*后面的/。

函数返回给定文件路径内所有子目录的List。将搜索整个文件树。

import os

def get_sub_directory_paths(start_directory, sub_directories):
    """
    This method iterates through all subdirectory paths of a given 
    directory to collect all directory paths.

    :param start_directory: The starting directory path.
    :param sub_directories: A List that all subdirectory paths will be 
        stored to.
    :return: A List of all sub-directory paths.
    """

    for item in os.listdir(start_directory):
        full_path = os.path.join(start_directory, item)

        if os.path.isdir(full_path):
            sub_directories.append(full_path)

            # Recursive call to search through all subdirectories.
            get_sub_directory_paths(full_path, sub_directories)

return sub_directories

在ipython中复制粘贴友好:

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

从打印(文件夹)输出:

['folderA', 'folderB']

我最近也遇到过类似的问题,我发现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获取关于条目对象的其他详细信息。