How to add a relative path in python to find image and other file with a short path?
29,631
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
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')
Related videos on Youtube
![Xiangwei Wang](https://lh6.googleusercontent.com/-uVbuEFUKT7M/AAAAAAAAAAI/AAAAAAAAABI/DmRpDQ8SDeM/photo.jpg?sz=256)
Author by
Xiangwei Wang
Updated on July 09, 2022Comments
-
Xiangwei Wang almost 2 years
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
? An error happens. Can add a relative path in python to find image with the short pathimages/image1.png
?I do not want to move my image folder into program folder nor change the path by
../images/image1.png
? -
Xiangwei Wang about 8 yearsThanks for your answer. After the modify, my program can find the image1.png by 'images/image1.png', however, there are many images in the folder named images, is there some way to make all images can be accessed by 'images/imagex.png'
-
joel goldstick about 8 years@XiangweiWang If you like the answer, press the checkmark
-
János Farkas about 8 years@joelgoldstick im not sure, but i think he will never accept this answer as solution :)
-
ElPapi42 about 4 yearsThis is not the best solution, this does not cover a case where this script is imported from other script.