python - 获取调用该函数的文件的绝对路径

标签 python path

我想创建一个 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/

相关文章:

python - 在 Python 中注册信号处理程序的正确方法是什么?

python - 仅使用 Python 标准库进行 html 到文本的转换

python - 如何比较包含整数的列表 A 和列表 B 并打印缺少的整数?

linux - 将任何当前目录 './' 添加到 Linux 中的搜索路径

c++ - 错误 C1083 无法打开包含文件 : 'IexBaseExc.h' : No such file or directory

java - java中Ubuntu服务器上的路径?

java - 创建文件和目录无法正常工作

python - 无法在 VS Code 中导入

python - Delphi 或 C 代码与 Python 脚本之间的桥梁

html - 预编译后 html 图像路径是否仍然有效?