我正在构建一个简单的助手脚本,用于将代码库中的两个模板文件复制到当前目录。但是,我没有存储模板的目录的绝对路径。我有一个相对路径从脚本,但当我调用脚本,它把它作为一个相对于当前工作目录的路径。是否有一种方法来指定这个相对url是来自脚本的位置?


当前回答

看到sys.path 在程序启动时初始化后,该列表的第一项路径[0]是包含用于调用Python解释器的脚本的目录。

使用此路径作为根文件夹,从中应用相对路径

>>> import sys
>>> import os.path
>>> sys.path[0]
'C:\\Python25\\Lib\\idlelib'
>>> os.path.relpath(sys.path[0], "path_to_libs") # if you have python 2.6
>>> os.path.join(sys.path[0], "path_to_libs")
'C:\\Python25\\Lib\\idlelib\\path_to_libs'

其他回答

假设当前的存档文件名为“Helper”,上面的目录名为“Workshop”,模板文件在\Workshop\Templates中,那么Python中的相对路径为“..\Templates”。

而不是使用

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

在公认的答案中,使用它会更健壮:

import inspect
import os
dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

因为使用__file__将返回加载模块的文件,如果它是从一个文件中加载的,所以如果从其他地方调用带有脚本的文件,则返回的目录将不正确。

这些答案提供了更多的细节:https://stackoverflow.com/a/31867043/5542253和https://stackoverflow.com/a/50502/5542253

以下是我的总结:

首先,定义名为relpath的工具函数,它将当前文件的相对路径转换为cwd的相对路径

import os
relpath = lambda p: os.path.normpath(os.path.join(os.path.dirname(__file__), p))

然后我们使用它来包装相对于当前文件的路径

path1 = relpath('../src/main.py')

你也可以调用sys.path.append()来导入相对于当前文件位置的文件

sys.path.append(relpath('..')) # so that you can import from upper dir

完整的示例代码:https://gist.github.com/luochen1990/9b1ffa30f5c4a721dab5991e040e3eb1

这是向系统路径集添加相对路径的简单方法。例如,对于目标目录比工作目录高一级(例如'/../')的常见情况:

import os
import sys
workingDir = os.getcwd()
targetDir = os.path.join(os.path.relpath(workingDir + '/../'),'target_directory')
sys.path.insert(0,targetDir)

对该解决方案进行了测试:

Python 3.9.6 |由conda-forge |打包(默认,2021年7月11日, 03:37:25) [MSC .1916 64位(AMD64)]

这段代码将返回主脚本的绝对路径。

import os
def whereAmI():
    return os.path.dirname(os.path.realpath(__import__("__main__").__file__))

这甚至可以在一个模块中工作。