[英]finding out absolute path to a file from python
If I have a file test.py
that resides in some directory, how can I find out from test.py
what directory it is in? 如果我有一个文件
test.py
驻留在某个目录中,我如何从test.py
找到它所在的目录? os.path.curdir
will give the current directory but not the directory where the file lives. os.path.curdir
将提供当前目录,但不提供文件所在的目录。 If I invoke test.py
from some directory foo
, os.curdir
will return foo
but not the path of test.py
. 如果我从某个目录
foo
调用test.py
, os.curdir
将返回foo
但不返回test.py
的路径。
thanks. 谢谢。
Here's how to get the directory of the current file: 以下是获取当前文件目录的方法:
import os
os.path.abspath(os.path.dirname(__file__))
the answer is to use: 答案是使用:
__file__
which returns a relative path. 返回相对路径。
os.path.abspath(__file__)
can be used to get the full path. 可以用来获得完整的路径。
The answers so far have correctly pointed you to os.path.abspath
, which does exactly the job you requested. 到目前为止,答案已经正确地指向了
os.path.abspath
,它完全符合您的要求。 However don't forget that os.path.normpath and os.path.realpath
can also be very useful in this kind of tasks (to normalize representation, and remove symbolic links, respectively) in many cases (whether your specific use case falls among these "many" is impossible to tell from the scant info we have, of course;-). 但是不要忘记os.path.normpath和
os.path.realpath
在这种任务中也很有用(分别规范化表示和删除符号链接)(无论你的具体用例是否属于当然,这些“很多”不可能从我们所掌握的信息中分辨出来;-)。
import os
dirname, filename = os.path.split(os.path.abspath(__file__))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.