Python os.path.dirname returns 更改目录时出现意外路径

Python os.path.dirname returns unexpected path when changing directory

目前我不明白,为什么蟒蛇 os.path.dirname 表现得像它那样。

假设我有以下脚本:

# Not part of the script, just for the current sample
__file__ = 'C:\Python\Test\test.py'

然后我尝试获取以下目录的绝对路径:C:\Python\doc\py

使用此代码:

base_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)) + '\..\doc\py\')

但是为什么方法os.path.dirname没有解析路径,打印出来(print (base_path):

C:\Python\Test\..\doc\py

我期望该方法将路径解析为:

C:\Python\Test\doc\py

我只知道 .NET Framework 的这种行为,即获取目录路径将始终解析完整路径并使用 ..\ 删除目录更改。我在 Python 中有什么可能做到这一点?

os.path.normpath() 将 return 规范化路径,所有对当前目录或父目录的引用都已删除或适当替换。

调查os.path.normpath

Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes.

os.path.dirname 以这种方式工作的原因是因为它不是很智能 - 它甚至适用于 URL!

os.path.dirname("http://www.google.com/test")  # outputs http://www.google.com

它只是在最后一个斜线之后砍掉任何东西。它不会查看最后一个斜杠之前的任何内容,因此它不在乎您是否在某处有 /../