Python操作系统路径目录名更改目录时返回意外路径

2024-09-28 23:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我不明白,为什么Pythonos.path.dirname的行为会像它一样。在

假设我有以下脚本:

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

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

使用此代码:

^{pr2}$

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

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

我希望该方法可以将路径解析为:

C:\Python\Test\doc\py

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


Tags: ofthepath方法pytest路径目录
2条回答

查看^{}

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

它只不过是在最后一个斜线后砍掉任何东西。它不查看最后一个斜杠之前的任何内容,因此它不关心是否有/../在某个地方。在

^{}将返回一个规范化路径,并适当删除或替换对当前或父目录的所有引用。在

相关问题 更多 >