1

I have a simple Tkinter desktop app and I recently made a .exe file of it using pyinstaller. However, when I want to copy a file it doesn't work because I always get the wrong absolute path. Doing the same but running the Python script, not the .exe file works fine. When I use the relative path it works fine in both the .exe and the python file. How can I fix this?

Code:

def load_map(RL_PATH, map_title):
    PATH = pathlib.Path(__file__).parent.absolute()
    shutil.copyfile(r'{}\Map Files\{}'.format(PATH, map_title),
        r'{}/Labs_Underpass_P.upk'.format(RL_PATH))

The error message I get from the .exe file:

Exception in Tkinter callback
Traceback (most recent call last):
  File "tkinter\__init__.py", line 1883, in __call__
  File "gui.py", line 154, in <lambda>
    def popular_maps_table(self, map_list):
  File "gui.py", line 134, in load_map_try
    try:
  File "load_map.py", line 13, in load_map
    shutil.copyfile(r'{}\Map Files\{}'.format(PATH, map_title),
  File "shutil.py", line 261, in copyfile
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Martin\\AppData\\Local\\Temp\\_MEI132082\\Map Files\\DribblingChallenge2.udk'

It seems like C:\\Users\\Martin\\AppData\\Local\\Temp\\_MEI132082 is the absolute path of the .exe file.

cconsta1
  • 737
  • 1
  • 6
  • 20
themm1
  • 137
  • 2
  • 10
  • 2
    Does this answer your question? [Determining application path in a Python EXE generated by pyInstaller](https://stackoverflow.com/questions/404744/determining-application-path-in-a-python-exe-generated-by-pyinstaller) – CryptoFool Mar 21 '21 at 17:20

1 Answers1

3

So I've figured it out. For the absolute path of exe file, sys.executable is required.

Code:

if getattr(sys, 'frozen', False):
    path = os.path.dirname(sys.executable)
elif __file__:
    path = os.path.dirname(__file__)
    shutil.copyfile(r'{}\Map Files\{}'.format(path, map_title),
        r'{}/Labs_Underpass_P.upk'.format(RL_PATH))

Original answer: Determining application path in a Python EXE generated by pyInstaller

dolgom
  • 611
  • 1
  • 11
  • 27
themm1
  • 137
  • 2
  • 10