RFVenter RFVenter - 2 months ago 11
Python Question

Path manipulation in python

I have looked on Stack Overflow everywhere but I cant find a solution to this problem.

Given that I have a folder/file as string:

how can I get the parent folder and its parent folder. In other words if I want to traverse up one level
or two levels
how can I get those string values from the original string path in python?

Please note that I don't simply want the pieces of the path (in other words not a list of
['path1', 'path2', 'path3']
) but instead


os.path.dirname() (doc) is the way to go. It returns the directory which contains the object pointed by the path:

>>> import os.path
>>> os.path.dirname('/path1/path2/path3/file')

In this case, you want the "grandparent" directory, so just use the function twice:

>>> parent = os.path.dirname('/path1/path2/path3/file')
>>> os.path.dirname(parent)

If you want to do it an arbitrary number of times, a function can be helpful here:

def go_up(path, n):
    for i in range(n):
        path = os.path.dirname(path)

    return path

Here are some examples:

>>> go_up('/path1/path2/path3/file', 1)
>>> go_up('/path1/path2/path3/file', 2)
>>> go_up('/path1/path2/path3/file', 3)