'Pyinstaller EXE's __file__ refers to a .py file
Situation: My Python script has a line of code that copies itself to another directory
shutil.copyfile(os.path.abspath(__file__), newPath)
Problem: The script is then compiled into an EXE and ran. The error given is as follows:
FileNotFoundError: No such file or Directory: "C:\Path\To\EXE\script.py"
As you can see, the EXE is looking for the .py version of itself (i.e. uncompiled version)
Question: Is there another Python command that can still let the executable find itself and not the .py version of itself?
Additional information: I was going to try to just replace .py with .exe and see if it works -- it would have if not for the program to fail if I change the name of the executable.
C:\ > script.exe
#Works as expected
C:\ > ren script.exe program.exe
C:\ > program.exe
FileNotFoundError: No such file or directory: "C:\script.py"
Solution 1:[1]
Try the following:
from os.path import abspath, splitext
fromfile_without_ext, ext = splitext(abspath(__file__))
shutil.copyfile(fromfile_without_ext + '.exe', newPath)
(Did not test it, but should work...)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dick Kniep |
