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

如何在python中添加相对路径以查找具有短路径的图像和其他文件?,python,path,relative-path,Python,Path,Relative Path,我的项目文件夹按以下方式排列: 项目文件夹->程序文件夹->程序 ->名为images->Image的图像文件夹 现在,当我试图在我的程序中用pathimages/image1.png处理图像时? 发生了一个错误。 可以在python中添加一个相对路径来查找具有短路径的图像images/image1.png import os script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in rel_pat

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

项目文件夹->程序文件夹->程序
->名为images->Image的图像文件夹
现在,当我试图在我的程序中用path
images/image1.png
处理图像时? 发生了一个错误。 可以在python中添加一个相对路径来查找具有短路径的图像
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)

我不想将图像文件夹移动到程序文件夹中,也不想通过
。/images/image1.png

更改路径,谢谢您的回答。修改后,我的程序可以通过“images/image1.png”找到image1.png,但是名为images的文件夹中有很多图像,是否有办法让所有图像都可以通过“images/imagex.png”@XiangweiWang访问如果您喜欢答案,请按checkmark@joelgoldstick我不确定,但我认为他永远不会接受这个答案作为解决方案:)这不是最好的解决方案,这不包括从其他脚本导入此脚本的情况。
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)