Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? An error happens. Can add a relative path in python to find image with the short path images/image1.png?

I do not want to move my image folder into program folder nor change the path by ../images/image1.png?

like image 683
Xiangwei Wang Avatar asked Oct 19 '25 08:10

Xiangwei Wang


1 Answers

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')
like image 140
János Farkas Avatar answered Oct 21 '25 22:10

János Farkas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!