如何在python中添加相对路径以查找具有短路径的图像和其他文件? [英] How to add a relative path in python to find image and other file with a short path?
本文介绍了如何在python中添加相对路径以查找具有短路径的图像和其他文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的项目文件夹按以下方式排列:
My project folder arrange in the following way:
Project folder-> Program folder->program
-> Image folder named images->image
现在,当我尝试在程序中处理路径为images/image1.png
的图像时,该怎么办?
发生错误.
可以在python中添加相对路径以查找短路径images/image1.png
的图片吗?
Now when I try to deal with a image in my program with path images/image1.png
?
An error happens.
Can add a relative path in python to find image with the short path images/image1.png
?
我不想将图像文件夹移动到程序文件夹中,也不想通过../images/image1.png
更改路径?
I do not want to move my image folder into program folder nor change the path by ../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变量作为图像的路径
and now u can use abs_file_path variable as path to your image
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中添加相对路径以查找具有短路径的图像和其他文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文