python abspath returning path twice

試著忘記壹切 提交于 2021-02-08 08:41:05

问题


I'm trying to get an absolute path of a relative path string with python but it keeps printing the path twice. For example:

self.path = 'Users/abdulahmad/Desktop'
self.actual_path = os.path.abspath(self.path)
print self.actual_path

my console prints

/Users/abdulahmad/Desktop/Users/abdulahmad/Desktop

and if I change the path to:

self.path = 'Desktop'

my console prints:

/Users/abdulahmad/Desktop/Desktop

shouldn't it just print /Users/abdulahmad/Desktop in both cases?


回答1:


Probably because the current working directory is /Users/abdulahmad/Desktop.

If you write for example path/to/file it means relative to current working directory and relative to /Users/abdulahmad/Desktop it would mean /Users/abdulahmad/Desktop/path/to/file.

If you read the python3 manual it actually shows an implementation of os.abspath(path) as being the same as os.path.normpath(os.path.join(os.getcwd(), path)). This can be used to get a path relative to arbitrarily provided path. (It also shows that you actually basically joins the current working directory and the supplied (relative) path)



来源:https://stackoverflow.com/questions/36085313/python-abspath-returning-path-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!