递归收益递归列出目录中的所有文件

首先,导入使用文件的库:

from os import listdir
from os.path import isfile, join, exists

一个辅助函数,只读取目录中的文件:

def get_files(path):
    for file in listdir(path):
        full_path = join(path, file)
        if isfile(full_path):
            if exists(full_path):
                yield full_path

另一个辅助函数只能获取子目录:

def get_directories(path):
    for directory in listdir(path):
        full_path = join(path, directory)
        if not isfile(full_path):
            if exists(full_path):
                yield full_path

现在使用这些函数递归获取目录及其所有子目录中的所有文件(使用生成器):

def get_files_recursive(directory):
    for file in get_files(directory):
        yield file
    for subdirectory in get_directories(directory):
        for file in get_files_recursive(subdirectory): # here the recursive call
            yield file

使用 yield from 可以简化此功能:

def get_files_recursive(directory):
    yield from get_files(directory)
    for subdirectory in get_directories(directory):
        yield from get_files_recursive(subdirectory)