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>You can use the <a href="https://docs.python.org/3.6/library/pathlib.html#module-pathlib" rel="nofollow"><code>pathlib</code></a> module:</p>

<pre><code>&gt;&gt;&gt; path = pathlib.PurePath('/file1/file2/file3/file')
&gt;&gt;&gt; path.parts
('/', 'file1', 'file2', 'file3', 'file')
&gt;&gt;&gt; os.path.join(*path.parts[:-2])
'/file1/file2'
</code></pre>

<p>So just put <code>path.parts[:-n]</code> for <code>n</code> levels up.</p>

<p>Alternatively you can use the <a href="https://docs.python.org/3.6/library/pathlib.html#pathlib.PurePath.parents" rel="nofollow"><code>parents</code></a> attribute:</p>

<pre><code>&gt;&gt;&gt; path = pathlib.PurePath('/file1/file2/file3/file4/file5/file6')
&gt;&gt;&gt; path.parents[0]
PurePosixPath('/file1/file2/file3/file4/file5')
&gt;&gt;&gt; path.parents[1]
PurePosixPath('/file1/file2/file3/file4')
&gt;&gt;&gt; path.parents[4]
PurePosixPath('/file1')
</code></pre>

<p>So to go up <code>n</code> levels just use <code>parents[n-1]</code>.</p>

<p>To convert a <code>*Path</code> object to a string just call <code>str</code> on it:</p>

<pre><code>&gt;&gt;&gt; str(path)
'/file1/file2/file3/file4/file5/file6'
</code></pre>

python