Python递归收益:递归列出目录中的所有文件
示例
首先,导入可处理文件的库:
from os import listdir fromos.pathimport 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): #在这里递归调用 yield file
可以使用yieldfrom以下命令简化此功能:
def get_files_recursive(directory): yield from get_files(directory) for subdirectory in get_directories(directory): yield from get_files_recursive(subdirectory)