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

Xia*_*ang 2 python path relative-path

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

Project folder-> Program folder->program
              -> Image folder named images->image
Run Code Online (Sandbox Code Playgroud)

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

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

小智 6

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)
Run Code Online (Sandbox Code Playgroud)

现在你可以使用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')
Run Code Online (Sandbox Code Playgroud)