How can I find script's directory with Python?
This question already has an answer here:
你需要在__file__
上调用os.path.realpath
,这样当__file__
是没有路径的文件名时,你仍然可以得到dir路径:
import os
print(os.path.dirname(os.path.realpath(__file__)))
I use:
import os
import sys
def get_script_path():
return os.path.dirname(os.path.realpath(sys.argv[0]))
As aiham points out in a comment, you can define this function in a module and use it in different scripts.
Try sys.path[0]
.
To quote from the Python docs:
As initialized upon program startup, the first item of this list, path[0]
, is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (eg if the interpreter is invoked interactively or if the script is read from standard input), path[0]
is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH
.
Source: https://docs.python.org/library/sys.html#sys.path
链接地址: http://www.djcxy.com/p/9290.html上一篇: 在bash中仅列出使用ls的目录:检查
下一篇: 我如何用Python找到脚本的目录?