Skip to content

Instantly share code, notes, and snippets.

@arush15june
Last active August 9, 2020 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arush15june/a986796480adcfa905bf6b127a8b6a42 to your computer and use it in GitHub Desktop.
Save arush15june/a986796480adcfa905bf6b127a8b6a42 to your computer and use it in GitHub Desktop.
Crawl within directory for files conditionally with pathlib
import pathlib
from typing import Callable, List
def crawl_dirs_for_condition(root: pathlib.Path, file_item_condition: Callable) -> List[pathlib.Path]:
"""Crawl root dir for files,
path file path to file_item_condition function,
if file_item_condition(file_path) returns true,
append file path to files.
Returns
-------
files: List[pathlib.Path]
All file paths inside root fulfilling file_item_condditions
"""
files = list()
def _crawl(root):
for item in root.iterdir():
if item.is_file():
if file_item_condition(item) and item not in files:
files.append(item)
elif item.is_dir():
_crawl(item)
_crawl(root)
return files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment