gpt4 book ai didi

Python os.path.dirname 更改目录时返回意外路径

转载 作者:行者123 更新时间:2023-11-30 23:02:26 24 4
gpt4 key购买 nike

目前我不明白,为什么 python 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

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

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

关于Python os.path.dirname 更改目录时返回意外路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34489459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com