Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Last active October 22, 2022 08:16
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 nikoheikkila/9252fa3c0c0e89a940218bd71e73ca31 to your computer and use it in GitHub Desktop.
Save nikoheikkila/9252fa3c0c0e89a940218bd71e73ca31 to your computer and use it in GitHub Desktop.
General directory scanner implementation in pure Python
class PathScanner:
input_paths: list[str]
allowed_extensions: tuple[str]
def __init__(self, input_paths: list[str], allowed_extensions: tuple[str]) -> None:
self.input_paths = input_paths
self.allowed_extensions = allowed_extensions
def fetch_paths(self) -> list[str]:
result: list[str] = []
for input_path in self.input_paths:
item = Path(input_path)
if item.is_dir():
result.extend(self.scan_directory(item))
if item.is_file():
result.extend(self.scan_file(item))
return result
def scan_directory(self, directory: Path) -> list[str]:
return map(
self.normalize_path, filter(self.is_accepted_filetype, directory.iterdir())
)
def scan_file(self, file: Path) -> list[str]:
return map(self.normalize_path, filter(self.is_accepted_filetype, [file]))
def normalize_path(self, path: Path) -> str:
return str(path.resolve())
def is_accepted_filetype(self, entry: Path) -> bool:
return entry.is_file() and entry.suffix in self.allowed_extensions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment