Reputation: 68
I know there are a lot of answers on this subject, but no one works once you compile a script in an executable.
In my python script, I create a file within the same directory of the script. to get the path of the current dir I use pathlib
basepath = Path(__file__).parent
filename='myfile'
filepath=os.path.join(basepath, filename)
if I print the directory I get the file wrote in the good directory and everything works fine within python (i.e desktop/myname/myscriptdir/myfile)
but once I "compile" with pyinstaller with --onefile, if I launch the executable, the directory will be like /var/folders/nr/w0698dl96j39_fq33lqd8pk80000gn/T/_MEIP12KxC/myfile
believed me, I tried a lot of various method (abspath, os.realpath..)to get the current dir, no one worked fine once in an executable file.
Upvotes: 1
Views: 1184
Reputation: 17344
When you compile an app using pyinstaller
with the --onefile
or -F
flag, the file that it creates is actually an archive file, like a .zip
file.
When you execute that file it launches a process that extracts itself into a temporary folder somewhere in your OS filesystem. This is the path that is reported when you use the __file__
variable in the compiled application.
It then continues to launch your application from there and the temporary directory becomes the runtime durectory for the duration of the apps life. When the app is finally closed it deletes the temporary runtime directory on it's way out.
Since this is the case there are alternatives.
path = '.'
#or
path = os.getcwd()
path = sys.executable
Upvotes: 2