RSSAmplifier

Recent articles from Everyday Superpowers

Finding the root of a project with pathlib

0
Sign in to vote or save

everydaysuperpowers.dev

April 24, 2025

Every now and then I’m writing code deep in some Python project, and I realize that it would be nice to generate a file at the root of a project.

The following is the way I’m currently finding the root folder with pathlib:

if __name__ == '__main__':
    from pathlib import Path
    project_root = next(
        p for p in Path(__file__).parents
        if (p / '.git').exists()
    )
    project_root.joinpath('output.text').write_text(...)

To explain what this does, let’s start on line 4:

  • Path(__file__) will create an absolute path to the file this Python code is in.
  • .parents is a generator that yields the parent folders of this path, so if this path is Path('/Users/example/projects/money_generator/src/cash/services/models.py') , it will generate:
    • Path('/Users/example/projects/money_generator/src/cash/services') then
    • Path('/Users/example/projects/money_generator/src/cash')
    • and so on
  • next() given an iterable, it will retrieve the next item in it It can also return a default value if the iterable runs out of items.[docs]
  • p for p in Path(__file__).parents is a comprehension that will yield each parent of the current file.
  • (p / '.git').exists() given a path p , it will look to see if the git folder ( .git ) exists in that folder
  • So, next(p for p in Path(__file__).parents if (p / '.git').exists()) will return the first folder that contains a git repo in the parents of the current Python file.

How do you accomplish this task?

Read the original on everydaysuperpowers.dev

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.