从python中找出文件的绝对路径
如果我有一个文件 test.py
驻留在某个目录中,我如何从 test.py
中找到它所在的目录? os.path.curdir 将给出当前目录,但不给出文件所在的目录。如果我从某个目录 foo
调用 test.py
,os.curdir
将返回 foo
但不是测试.py
。
谢谢。
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? os.path.curdir
will give the current directory but not the directory where the file lives. If I invoke test.py
from some directory foo
, os.curdir
will return foo
but not the path of test.py
.
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
获取当前文件所在目录的方法如下:
Here's how to get the directory of the current file:
答案是使用:
它返回相对路径。
可用于获取完整路径。
the answer is to use:
which returns a relative path.
can be used to get the full path.
到目前为止的答案已经正确地将您指向 os.path.abspath ,它完全可以完成您所请求的工作。但是不要忘记 os.path.normpath 和 os.path.realpath 在许多情况下(无论您的具体用例是否属于当然,从我们掌握的有限信息中不可能分辨出这些“许多”;-)。
The answers so far have correctly pointed you to
os.path.abspath
, which does exactly the job you requested. However don't forget that os.path.normpath andos.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
有很多处理问题的工具与路径并获取有关路径的信息。特别是,您想要:
os.path
has lots of tools for dealing with paths and getting information about paths.Particularly, you want: