【问题标题】:Get the path of the current Python file获取当前 Python 文件的路径
【发布时间】:2021-11-02 20:39:35
【问题描述】:

我正在尝试获取当前运行文件的目录路径。例如,如果我有以下文件:X/foo.pyY/bar.py,并且我正在运行 python3 foo.pyfoo.py 导入 bar.py,并且在 bar.py 中我得到父目录,我希望它是 Y而不是 X。我该怎么做?目前,我通过path = pathlib.Path(__file__).parent.resolve() 得到 X

【问题讨论】:

  • bar.__file__,或者如果你在bar,只需__file__

标签: python file directory path working-directory


【解决方案1】:

这里已经回答了这个问题: Find the current directory and file's directory

你需要做的是:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

这将返回当前 py 文件的绝对路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多