【复制可用】Python查找某个目录下,某种类型的所有文件

【复制可用】Python查找目录下,某种类型的所有文件

from typing import List, Union
from pathlib import Path
def find_files(root_dir: Union[str, Path], suffix_list: list) -> List[Union[str, Path]]:
    """ 返回root目录下所有以{suffix_list}为后缀的文件路径
    Args:
        root_dir (Union[str, Path]): 需要搜索的目录路径
        suffix_start_with (list): 文类型的后缀列表,例如:['.doc', '.docx']

    Returns:
        List[Union[str, Path]]: 匹配文件的文件路径列表,路径类型和传入的root_dir的类型保持一致
    """
    is_path_type_path = isinstance(root_dir, Path) # 判断传入的类型
    if not is_path_type_path: # 转换为Path类型的路径
        root_dir = Path(root_dir)

    res_paths = [] # the result of path list
    if root_dir.is_file(): # file
        if root_dir.suffix in suffix_list:
            res_paths.append(root_dir if is_path_type_path else str(root_dir))
    else: # directory
        for path in root_dir.iterdir():
            res_paths.extend(find_files(path, suffix_list))
    return res_paths

你可能感兴趣的:(python,实用为王,python)