2

I have written code in python which opens up a template excel file. Everyday, a midnight, it copies that template into a new excel file where the code will record data into it for that day. My goal is to create a single executable file containing my code AND the template excel file using pyinstaller.

Basically I want to be able to open the template excel file regardless of whether the computer contains the file or not by bundling the excel file into the exe file obtained from pyinstaller:

Right now I open the excel file as shown below:

import os
import openpyxl

theFile = openpyxl.load_workbook(os.getcwd()+"\templateExcel.xlsx")
currentSheet = theFile[theFile.sheetnames[0]]

However, when I include the excel file to the pyinstaller command as --add-data "templateExcel.xlsx;templateExcel.xlsx, and run the exe file, it is not able to detect the location of the templateExcel file. I understand that by running on a different computer, the os.getcwd() gives a different path so it would obviously not be able to open the excel file. Hence I needed a way to bundle the excel file into the exe file such that the python code can find it regardless of the computer.

Jeff Boker
  • 803
  • 1
  • 9
  • 25

2 Answers2

1

You can use; Adding a data file in Pyinstaller using the onefile option
Summarly:

pyinstaller --onefile --nowindow --add-data text.txt;included winprint.py --distpath .

and sample python script:

import os 
import sys

os.chdir(sys._MEIPASS)
os.system('included\\text.txt')
Sezer BOZKIR
  • 534
  • 2
  • 13
  • You don't need to chdir, you could have appended the relative path ('included\\text.txt') to the sys._MEIPASS. Moreover, you shouldn't, unless you are sure that's what you want. – Guy Tabak Apr 15 '20 at 19:33
0

Please note: When using "getcwd()" you won't receive the desired outcome you were looking for, it will get you the place from which you have executed your exe file.

For example, look at the following long module:

from os import getcwd
print(getcwd())

If you execute it from different locations, you will get different results: enter image description here

Had PyInstaller worked like you assume it would (placing the file relative to some module) you could have used file instead of getcwd() as it indicated where the module resides (which is constant, unlike the location from which the exe is executed), but it doesn't.

Any way, @Sezer BOZKIR's answer should suffice, note the comment I added there.

Guy Tabak
  • 128
  • 7