pythonbuildfilepathos.pathdirname

Python idiom to get same result as calling os.path.dirname multiple times?


I find myself needing to get a parent directory of a python file in a source tree that is multiple directories up with some regularity. Having to call dirname many times is clunky.

I looked around and was surprised to not find posts on this.

The general scenario is:

import os.path as op
third_degree_parent = op.dirname(op.dirname(op.dirname(op.realpath(__file__))))

Is there a more idiomatic way to do this that doesn't require nested dirname calls?


Solution

  • Normalize a relative path; os.pardir is the parent directory, repeat it as many times as needed. It is available via os.path.pardir too:

    import os.path as op
    
    op.abspath(op.join(__file__, op.pardir, op.pardir, op.pardir))