I'm trying to create an exe out of a python script that also makes use of an excel file. But everytime I run the exe, I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'Example.xlsx'
I really don't understand what I'm doing wrong, hope you can help me. My folder contains the following three files:
main.py
functions.py
Example.xlsx
Next, I run pyinstaller in the terminal:
pyinstaller --onefile --add-data "Example.xlsx:." main.py
It then creates the dist directory with the main exe in it. But when I run it, it gives me the mentioned error. My main.spec file shows the following for 'datas', what I think is right:
a = Analysis(...,
datas=[('210307 Valuation portfolio (HC).xlsx', '.')],
...)
What am I doing wrong here?
This is because pyinstaller extracts to a random temporary location, then runs your file.
This location is accessible using the sys._MEIPASS
location.
I came across a helper function a couple years ago that makes determining this location during development and deployment quite easy:
import sys, os
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
To use it, give the function the file name, and it will return an absolute path.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.