How to add a relative path in python to find image and other file with a short path?

戏子无情 提交于 2020-05-28 00:48:18

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/36476659/how-to-add-a-relative-path-in-python-to-find-image-and-other-file-with-a-short-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!