finding absolute path from a relative path in python

余生颓废 提交于 2019-12-12 14:06:56

问题


my question is pretty much what the title suggests. my research has led me to try something like this:

import os
pathname = os.path.abspath("some/relative/directory")
print pathname

this problem is that whenever i do something like this, it simply returns whatever relative directory i gave it preceded by my python directory. for example:

C:\Python27\some\relative\directory

which is not even an existing directory on my computer. i understand that the python interpreter searches the working directory by default, but what i'd like to do is have it search my entire computer for an absolute path that contains the partial directory i specify.

the purpose of this is for me to create an exe (using py2exe) that can search for an arbitrary directory on any computer. is there a method for doing this in the standard library or through some available module - or would i have to implement the algorithm myself?


回答1:


abspath is based on getcwd. Most likely, your current working directory simply isn't what you expect.

You can change the code that launches your script, change directories manually, or just use chdir in Python.




回答2:


Did you try os.path.realpath("my/relative/dir")? Actually it seems the directory may not exist, but if it does, it will resolve symbolic links and whatnot.



来源:https://stackoverflow.com/questions/7909300/finding-absolute-path-from-a-relative-path-in-python

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