Traverse Directory and Find Matching File Paths

  • Share this:

Code introduction


This function will traverse the given root directory and its subdirectories, and return all file paths that match the regular expression pattern.


Technology Stack : os, re

Code Type : Function

Code Difficulty :


                
                    
import os
import re

def find_files(root_path, pattern):
    """
    遍历给定根目录,返回匹配正则表达式的所有文件路径。

    :param root_path: str, 根目录路径
    :param pattern: str, 正则表达式模式
    :return: list, 匹配的文件路径列表
    """
    results = []
    for root, dirs, files in os.walk(root_path):
        for file in files:
            if re.match(pattern, file):
                results.append(os.path.join(root, file))
    return results                
              
Tags: