简体   繁体   English

从python中找出文件的绝对路径

[英]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.pyos.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.normpathos.path.realpath在这种任务中也很有用(分别规范化表示和删除符号链接)(无论你的具体用例是否属于当然,这些“很多”不可能从我们所掌握的信息中分辨出来;-)。

import os
dirname, filename = os.path.split(os.path.abspath(__file__))

os.path has lots of tools for dealing with paths and getting information about paths. os.path有很多工具可以处理路径和获取路径信息。

Particularly, you want: 特别是,你想要:

os.path.abspath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM