Search code examples
pythonpyinstallerexe

How do you convert a python script that reads a text file into a working exe


I created an application that reads a text file to get a digit (1 or 0) to execute some code (it runs like a save file since I want the value to be changed permanently, not just while the script is running), but when I use pyinstaller to convert it to a standalone exe file I get a Fatal Error saying that it cannot run the script. Previous compilations from before I added this feature worked, so I know it's something to do with reading that text file.

Note: I tried using a .py file instead of a .txt. While it worked as a script, the same error came up after compilation.

this is what I type into an elevated command prompt:

pyinstaller --onefile --add-data save.txt;.' file.py

Solution

  • You can not edit the data files that you have bundled with your application using --add-data in pyinstaller's --onefile method as it unpacks all the files into a temporary directory when executed, therefore the file wiil not be found in the current directory as the application demands, so you end up with the Fatal Error.

    To get around this, refer to this post, use that function in your code and send your relative path into it, so as to get the absolute path of the file when the application is run. Remember, the changes that you make will be lost after you close the application, as these files are treated as "data files", they are not intended to be modified, so the binary will create a new copy of initial file on every application launch.

    If you want it to permanently be stored somewhere, you can implement the file creation (if it doesn't exist) form the script itself, by creating a directory in the AppData folder and save the file there.