emilk
emilk

Reputation: 106

Setting working directory of a converted .py file to .exe file

I am having issues with a converted .exe file. It does not find my excel file.

I have the following code

import pandas as pd
import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

#Load data
data = pd.read_excel("data.xlsx")
...

The second part of the code (abspath, dname, os.chdir(dname) is setting the path to the location of the .py file. Hence, having the .py file and .xlsx file together will always make it find it no matter the location.

Then I convert it to .exe using

pyinstaller --hidden-import=pandas --onefile script.py

To make my script.py work, I have to have the data.xlsx file in the same folder as the script.py file.

I would assume dragging the .exe file out of the dir folder into the same location at as the .xlsx file would make it run but running the .exe files returns the following error:

Failed to execute script script. No such file 'data.xlsx' in directory.

How can I make it read my excel file no matter the location of the '.exe+.xlsx' folder?

Upvotes: 2

Views: 2322

Answers (1)

Kemp
Kemp

Reputation: 3649

The problem you're encountering is that when you run the executable the files are extracted to a temporary directory and run from there. This means that i) the current/working directory is the temporary directory and ii) the location of the program that is actually executing is also that temporary directory, so neither way of obtaining the path will do what you want.

However, when run as an executable some additional values are available via the sys module. The ones that are useful in this case are sys.frozen, which is set to True, and sys.executable, which is set to the location of the executable that the user ran.

In the past I've found the path I need in the following way:

if getattr(sys, 'frozen', False):
    app_path = os.path.dirname(sys.executable)
else:
    app_path = os.path.dirname(os.path.abspath(__file__))

where app_path will now be the directory of the script or executable. You can then use this as the basis of accessing other files.

Upvotes: 6

Related Questions