How to access .png file in folder from a python file if both are compiled together into .exe file using pyinstaller

Viewed 143

When I was compiling the desired folder and Python program into an executable using Pyinstaller I used datas = [("C:Users/Snoxzy/project/data", "data")],... line in .spec file to include 'data' folder into executable that would also be accessible as 'data' in bundle that pyinstaller would create during compilation. My Python program references a .png file from 'C:Users/Snoxzy/project/data' folder and that won't work if I later delete that .png file. If I was able to reference the newly created 'data' folder instance of 'C:Users/Snoxzy/project/data' in bundle that pyinstaller created I could later delete the original .png file and executable should still be working because I am referencing .png file from a 'data' folder that is integrated directly into executable, but I don't know how to do that. More precisley, the part of code where I refrence .png file is: field = ImageTk.PhotoImage(Image.open('C:Users/Snoxzy/project/data/other/field.png')). What should I use insted of this 'C:Users/Snoxzy/project/data/other/field.png' to access bundle folder 'data'?

1 Answers

You can use sys.executable to find the path to python.exe in your executable. Then use os module to build out the path to your .png. This example will work if you have your data folder in the same dir as python.exe.

import sys
import os

field = os.path.join(os.path.dirname(sys.executable), ('data\\' 'other\\' 'field.png'))
Related