擅长:python、mysql、java
<p>您可以使用<code>split</code>函数两次:</p>
<pre><code>os.path.split(os.path.split(a)[0])[0]
</code></pre>
<p>这是因为<code>os.path.split()</code>返回一个包含两个项的元组,head和tail,通过取其中的<code>[0]</code>我们将得到head。然后再次拆分并使用<code>[0]</code>再次获取第一项。你知道吗</p>
<p>或者将路径与父目录连接两次:</p>
<pre><code>os.path.abspath(os.path.join(a, '..', '..'))
</code></pre>
<p>您可以轻松地创建一个函数,该函数将按您所需的步骤后退:</p>
<pre><code>def path_split(path, steps):
for i in range(steps + 1):
path = os.path.split(path)[0]
return path
</code></pre>
<p>所以呢</p>
<pre><code>>>> path_split("C:\Users\Me\level1\level2\level3\level4\level5\level6\level7\level8", 2)
"C:\Users\Me\level1\level2\level3\level4\level5\level6\"
</code></pre>