更改目录时,Python os.path.dirname返回意外路径 [英] Python os.path.dirname returns unexpected path when changing directory
问题描述
目前我不明白,为什么蟒蛇os.path.dirname
表现得像它一样.
Currently I do not understand, why pythons os.path.dirname
behave like it does.
假设我具有以下脚本:
# Not part of the script, just for the current sample
__file__ = 'C:\\Python\\Test\\test.py'
然后我尝试获取以下目录的绝对路径:C:\\Python\\doc\\py
Then I try to get the absolute path to the following directory: C:\\Python\\doc\\py
使用以下代码:
base_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)) + '\\..\\doc\\py\\')
但是为什么方法os.path.dirname
无法解析路径并打印出(print (base_path)
:
But why does the method os.path.dirname
does not resolve the path, and print out (print (base_path)
:
C:\ Python \ Test \ .. \ doc \ py
C:\Python\Test\..\doc\py
我期望该方法可以解析以下路径:
I've expected the method to resolve the path to:
C:\ Python \ Test \ doc \ py
C:\Python\Test\doc\py
我只是从.NET Framework中知道此行为,因此获取目录路径将始终解析完整路径并使用..\\
删除目录更改.我在Python中有什么可能做到这一点?
I just know this behaviour from the .NET Framework, that getting directory paths will always resolve the complete path and remove directory changes with ..\\
. What do I have in Python for possibilities to do this?
推荐答案
通过折叠冗余分隔符和上级引用来标准化路径名,以便A//B,A/B/,A/./B和A/foo/../B都成为A/B.此字符串操作可能会更改包含符号链接的路径的含义.在Windows上,它将正斜杠转换为反斜杠.
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!
The reason os.path.dirname
works the way it does is because it's not very smart - it even work for URLs!
os.path.dirname("http://www.google.com/test") # outputs http://www.google.com
它只是在最后一个斜杠之后砍掉任何东西.它不会在最后一个斜杠前显示任何内容,因此它并不关心您是否在某个地方有/../
.
It simply chops off anything after the last slash. It doesn't look at anything before the last slash, so it doesn't care if you have /../
in there somewhere.
这篇关于更改目录时,Python os.path.dirname返回意外路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!