Tim Wilder Tim Wilder - 4 years ago 156
Python Question

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?

Answer Source

Normalize a relative path; ../ is the parent, repeat it as many times as needed:

import os.path as op

op.abspath(op.join(__file__, '../../..'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download