Skip to content

Instantly share code, notes, and snippets.

@shollingsworth
Last active June 16, 2022 18:42
Show Gist options
  • Save shollingsworth/32b019d2b14487204ebe10bbf07bfc18 to your computer and use it in GitHub Desktop.
Save shollingsworth/32b019d2b14487204ebe10bbf07bfc18 to your computer and use it in GitHub Desktop.
Recursively search for a file in a directory tree.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Recursively search for a file in a directory tree.
"""
import argparse
from pathlib import Path
def iter_parents(path: Path, args):
"""Iterate parents."""
p = path.parent
while p != Path('/'):
if p.joinpath(args.search_for).exists():
yield p.joinpath(args.search_for)
break
p = p.parent
yield from iter_parents(p, args)
def run(args):
"""Run."""
args.path = args.path.expanduser()
plist = list(iter_parents(args.path, args))
if not plist:
raise SystemExit("No matches found.")
print(plist[0])
def main():
"""Run main function."""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__,
)
parser.add_argument(
"path",
help="Path to search",
type=Path,
)
parser.add_argument(
"search_for",
help="File to search for",
type=Path,
)
args = parser.parse_args()
run(args)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment