Path manipulation in python
<p>I have looked on Stack Overflow everywhere but I cant find a solution to this problem.</p>

<p>Given that I have a folder/file as string: <code>"/path1/path2/path3/file"</code> how can I get the parent folder and its parent folder. In other words if I want to traverse up one level <code>"/path1/path2/path3"</code> or two levels <code>"/path1/path2"</code> how can I get those string values from the original string path in python?</p>

<p>Please note that I <strong>don't simply want the pieces</strong> of the path (in other words not a list of <code>['path1', 'path2', 'path3']</code>) but instead <code>"/path1/path2/path3"</code>.</p>

<p>Thank you </p>

<p><code>os.path.dirname()</code> (<a href="https://docs.python.org/2/library/os.path.html#os.path.dirname" rel="nofollow"><em>doc</em></a>) is the way to go. It returns the directory which contains the object pointed by the path:</p>

<pre><code>&gt;&gt;&gt; import os.path
&gt;&gt;&gt; os.path.dirname('/path1/path2/path3/file')
'/path1/path2/path3'
</code></pre>

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

<pre><code>&gt;&gt;&gt; parent = os.path.dirname('/path1/path2/path3/file')
&gt;&gt;&gt; os.path.dirname(parent)
'/path1/path2'
</code></pre>

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

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

    return path
</code></pre>

<p>Here are some examples:</p>

<pre><code>&gt;&gt;&gt; go_up('/path1/path2/path3/file', 1)
'/path1/path2/path3'
&gt;&gt;&gt; go_up('/path1/path2/path3/file', 2)
'/path1/path2'
&gt;&gt;&gt; go_up('/path1/path2/path3/file', 3)
'/path1'
</code></pre>

python