擅长:python、mysql、java
<p>这两件事是不相等的。如果您阅读<a href="https://docs.python.org/2/library/os.path.html" rel="nofollow noreferrer">documentation</a>,您将看到<code>dirname</code>只是返回您提供的路径的目录。你知道吗</p>
<p>所以<code>os.path.dirname("/foo/bar/file.txt")</code>将返回<code>/foo/bar</code>,<code>os.path.dirname("/foo/bar/")</code>也将返回<code>/foo/bar</code></p>
<p>顾名思义,<code>os.path.join</code>将路径片段连接在一起。你知道吗</p>
<p>所以如果我想得到<code>/foo/bar/file.txt</code>,我可以使用<code>os.path.join("/foo/bar/", "file.txt")</code>。在您给出的示例中,<code>os.path.join("/foo/bar/", os.pardir)</code>将给出<code>/foo/bar/..</code>。你知道吗</p>
<p>另一种常用的方法是:</p>
<pre><code>parent, _ = os.path.split("/foo/bar/file.txt")
</code></pre>
<p>其中<code>parent</code>是父目录,分配给<code>_</code>的值是<code>file.txt</code>。原因是<code>split</code>和<code>dirname</code>在做两件稍有不同的事情。<code>split</code>返回父目录的名称和文件名,而<code>dirname</code>只返回第一部分,基本上是上面一行的速记方法。你知道吗</p>
<p>关于<code>pardir</code>的用例并不多。如果您想看一些,请查看<a href="http://www.programcreek.com/python/example/448/os.pardir" rel="nofollow noreferrer">this</a>。你知道吗</p>