Xiangwei Wang
Xiangwei Wang

Reputation: 161

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?

Upvotes: 4

Views: 43696

Answers (1)

János Farkas
János Farkas

Reputation: 471

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')

Upvotes: 9

Related Questions