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

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


当前回答

虽然这个问题很久以前就有答案了。我想推荐使用pathlib模块,因为这是在Windows和Unix操作系统上工作的一种健壮的方式。

要获取特定目录下的所有路径,包括子目录:

from pathlib import Path
paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))

# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix

etc.

其他回答

谢谢你们的建议,伙计们。我遇到了软链接(无限递归)作为dirs返回的问题。Softlinks吗?我们不想要臭软链接!所以…

这只是渲染dirs,而不是软链接:

>>> import os
>>> inf = os.walk('.')
>>> [x[0] for x in inf]
['.', './iamadir']

虽然这个问题很久以前就有答案了。我想推荐使用pathlib模块,因为这是在Windows和Unix操作系统上工作的一种健壮的方式。

要获取特定目录下的所有路径,包括子目录:

from pathlib import Path
paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))

# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix

etc.

函数返回给定文件路径内所有子目录的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']

如果您需要一个递归的解决方案来查找子目录中的所有子目录,请使用前面建议的walk。

如果您只需要当前目录的子目录,请将os. xml目录合并在一起。使用os.path.isdir