0

I have 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 wrong absolute path. Doing the same but running the python script, not the .exe file works fine. When I use relative path it works fine in both .exe and python file. How can I fix it?

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))

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.

themm1
  • 97
  • 9
  • 1
    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

1

So I've figured it out. For absolute path of exe file is sys.executable 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

themm1
  • 97
  • 9