python - 如何在 python 中添加相对路径以查找具有短路径的图像和其他文件?

标签 python path relative-path

我的项目文件夹按以下方式排列:

Project folder-> Program folder->program
              -> Image folder named images->image

现在,当我尝试使用路径 images/image1.png 处理程序中的图像时? 发生错误。 可以在 python 中添加相对路径来查找具有短路径 images/image1.png 的图像吗?

我不想将我的图像文件夹移动到程序文件夹中,也不想通过 ../images/image1.png 更改路径?

最佳答案

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "../images/image1.png"
abs_file_path = os.path.join(script_dir, rel_path)

现在您可以使用 abs_file_path 变量作为图像的路径

import os
script_dir = os.path.dirname(__file__)
rel_path = "../images/"
abs_file_path = os.path.join(script_dir, rel_path)
current_file ="image" + str(X) +".png"
file = open(abs_file_path+current_file,'r')

关于python - 如何在 python 中添加相对路径以查找具有短路径的图像和其他文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36476659/

相关文章:

python - 使用 requests.get() 时缺少 Cookie 的某些部分?

python - 评估目录中的文件

python - 将 Python int 转换为大端字节串

javascript - 无法从 Angular 路由器获取路径或网址

类内嵌套函数内的 Python 作用域?

Django,无法在子文件夹中创建应用程序

powershell - 为什么 Write-Host "$PSCommandPath"没有输出我当前的路径?

python - 尝试从目录外部导入时出现 ModuleNotFoundError

python - 如何在 Visual Studio 中使用 python 设置相对路径?

c# - 创建位图时的相对路径