[英]How to add a relative path in python to find image and other file with a short path?
My project folder arrange in the following way: 我的项目文件夹按以下方式排列:
Project folder-> Program folder->program
-> Image folder named images->image
Now when I try to deal with a image in my program with path images/image1.png
? 现在,当我尝试使用路径
images/image1.png
处理程序中的images/image1.png
? An error happens. 发生错误。 Can add a relative path in python to find image with the short path
images/image1.png
? 可以在python中添加相对路径以使用短路径
images/image1.png
查找图像吗?
I do not want to move my image folder into program folder nor change the path by ../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)
and now u can use abs_file_path variable as path to your image 现在您可以使用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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.