[英]Get the path of the current Python file
I am trying to the get the path of the directory of the current running file.我正在尝试获取当前运行文件的目录路径。 For example, if I the following files:
X/foo.py
and Y/bar.py
, and I am running python3 foo.py
and foo.py
imports bar.py
, and in bar.py
I get the parent directory, I want it to be Y and not X. How do I do that?例如,如果我有以下文件:
X/foo.py
和Y/bar.py
,并且我正在运行python3 foo.py
和foo.py
导入bar.py
,并且在bar.py
我得到父目录,我希望它是 Y 而不是 X。我该怎么做? currently, I get X with path = pathlib.Path(__file__).parent.resolve()
目前,我用
path = pathlib.Path(__file__).parent.resolve()
得到 X
This question already was answered here: Find the current directory and file's directory这个问题已经在这里回答: 查找当前目录和文件的目录
What you need to do is the following:您需要做的是:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
This will return the absolute path to the current py-file.这将返回当前 py 文件的绝对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.