遞迴收益遞迴列出目錄中的所有檔案

首先,匯入使用檔案的庫:

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)