更改目录时,Python os.path.dirname返回意外路径 [英] Python os.path.dirname returns unexpected path when changing directory

查看:264
本文介绍了更改目录时,Python os.path.dirname返回意外路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

查看 os.path.normpath

通过折叠冗余分隔符和上级引用来标准化路径名,以便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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆