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

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))

Someone else added an answer in 2018, 4 years later, so why not add mine. The other answers are either long or become long if a larger number of parents are required. Let's say you need 7 parents. This is what I do

os.path.abspath(__file__ + 8 * '/..')

Note the extra (8=7+1) to remove 7 parents as well as the file name. No need for os.path.pardir as abspath understands /.. universally and will do the right thing. Also has the advantage that the number of parents can be dynamic, determined at run-time.

In comparison, the equivalent using the accepted answer (longer and less obvious):

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