我想创建一个 util 函数,它返回文件的绝对路径(该函数已被调用),但是我没有找到这样做的方法。
为了获得更好的画面,这就是我想要实现的目标。
假设我有以下目录结构:
core/
utils/
__init__.py
files.py
__init__.py
service.py
其中files.py
包含
import os
def get_current_dir():
return os.path.abspath(os.path.dirname(__file__))
和service.py
包含
from utils.files import get_current_dir
print(get_current_dir())
预期的结果并非理想的结果。
我想要实现的目标:/usr/src/app/core
实际输出:/usr/src/app/core/utils
我一直在这里寻找许多答案,但没有一个有使用函数来确定路径的示例。
有什么方法或者至少有可能实现我正在寻找的东西吗?
谢谢!
最佳答案
您可以简单地将 __file__
作为参数传递
在文件.py
import os
def get_current_dir(file):
return os.path.abspath(os.path.dirname(file))
服务中.py
from utils.files import get_current_dir
print(get_current_dir(__file__))
关于python - 获取调用该函数的文件的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47409365/