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>additionally to all other answers, you can also use <a href="https://docs.python.org/2/library/os.path.html#os.path.join" rel="nofollow">os.path.join</a> function with the <code>os.path.pardir</code> variable which usually equals <code>..</code>.</p>

<pre><code>&gt;&gt;&gt; path = "some/random/path/to/process"
&gt;&gt;&gt; parent = os.path.pardir
&gt;&gt;&gt; grand_parent_path = os.path.join(path, parent, parent)
&gt;&gt;&gt; grand_parent_path
'some/random/path/to/process\\..\\..'
</code></pre>

<p>If you don't want to repeat <code>parent</code> several times, you can use a multipled list:</p>

<pre><code>&gt;&gt;&gt; os.path.join(path, *([parent] * 3))
'some/random/path/to/process\\..\\..\\..'
</code></pre>

<p>The result is quite ugly, so you can use the <a href="https://docs.python.org/2/library/os.path.html?highlight=os.path.realpath#os.path.normpath" rel="nofollow">os.path.normpath</a> function to make it prettier:</p>

<pre><code>&gt;&gt;&gt; os.path.normpath(os.path.join(path, *([parent] * 3)))
'some\\random'
</code></pre>

<p><strong>Important note</strong>: Doing so, you are sure your code is portable</p>

python