I built a program that needs to be started at window startup and it has problem when loading a file.
for example, let's say that the path of my app is :
c:\dir1\dir2\app.exe
This app.exe is built by cx_freeze.
And there is a file named :
c:\dir1\dir2\file.json
To make this app run at the beginning of the startup of window, I made a shortcut in the startup directory, and editted the registry using winreg
.
The problem is : my app has a code that is named :
file = open(os.getcwd() + '/file.json','r')
And when this runs at startup, the path is where the shortcut is, not c:\dir1\dir2\
.
Since this app should be distributed to several people, I cannot fix the absolute path by code and that is the most problematic.
What I want is to make my app somehow read c:\dir1\dir2\
when the window start, by making txt file in c:, etc. What is the general solution of this problem ? I think it is matter of my lack of knowledge, not difficulty of problem.
I think the current working directory is not c:\dir1\dir2\
but a different directory where the startup script runs. Try using the value of the __file__
variable and get that path's parent instead of os.getcwd()
.
Example:
import sys
from os import getcwd
from pathlib import Path
a = getcwd()
this_file_path = sys.executable if getattr(sys, 'frozen', False) else __file__
b = Path(this_file_path).parent.absolute()
print(a)
print(b)
upd: I've updated the code snipped based on Python cx_Freeze name __file__ is not defined that stated that __file__
variable might be unavailable or might have unexpected value after freezing.
I've also tested the above solution by freezing my example code with cx-freeze.
The result was:
C:\path\the\executable\was\called\from
C:\path\the\executable\resides