Skip to content

Instantly share code, notes, and snippets.

@m3ck0
Last active March 15, 2021 05:17
Show Gist options
  • Save m3ck0/c7ab3f06dce8048a2304aaed1d6a6283 to your computer and use it in GitHub Desktop.
Save m3ck0/c7ab3f06dce8048a2304aaed1d6a6283 to your computer and use it in GitHub Desktop.
utility function to recursively detect file names by pattern
import re
from typing import List
from pathlib import Path
def match_files(root: Path, pattern, exclude_items: List[str]) -> List[Path]:
"""
utility function to recursively detect file names by pattern.
>>> match_files(Path.cwd(), re.compile('.*?\.py'), ['__pycache__'])
:param root: initial dir from where files are recursively discovered
:param pattern: compiled regex pattern to which file name should be matched
:param exclude_items: list of file / dir names to be excluded
:return: list of files detected
"""
files = list()
for item in root.iterdir():
if item.name in exclude_items:
continue
elif item.is_file() and pattern.match(item.name):
files.append(item)
elif item.is_dir():
files.extend(match_files(item, pattern, exclude_items))
return files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment