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

2024-04-25 19:29:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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


Tags: 项目图像image路径project文件夹png方式
1条回答
网友
1楼 · 发布于 2024-04-25 19:29:50
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')

相关问题 更多 >