How to make compiled executable file write data?

83 Views Asked by At

Some time ago I started working on some software. For the software to work properly I required the code to write data to different python files. The data writing and opening commands I had implemented were:

import sys
sys.path.append('path_to_python_files')
from pythonproject import *
var1 = open('pythonproject.py',w)
var1.write(str('something'))
var1.close()

Afterwards I had converted the .py project to an executable file with PyInstaller. Finally I had my code in executable format. Although the code always used to, and still does, work in visual code, it's .exe file doesn't write any data whatsoever. On top of that I had finally compliled the entire pack with Inno and InstallForge. Both created files that couldn't be opened. What did I mess up? I have spent hours writing this software for it to eventually become some weirdly bugged .exe. I'd really appreciate someone's insight.

(My expectations were the code would alter the state of the python files, but that only was truth in Visual Code, where the python files were in the same directory as the software python file. P.S. I did try to put the .exe file and the extra python files in the same directory after converting to .exe, and using the "from . import something" method, but that didn't work as well.)

1

There are 1 best solutions below

0
Dave On

It seems that there is some confusion in handling files and directories in your Python code and the executable generated by PyInstaller. Let's try to see if this solves the problem. In your code, you used 'w' as the mode to open the file. However, the correct mode for writing a file is 'w', not 'w'. The mode 'w' should cause an error. So, the code should be:

var1 = open('pythonproject.py', 'w')

When you use PyInstaller to create an executable file, the path to files can change. Make sure that the path specified for opening the file is correct in the executable. You may need to use the sys._MEIPASS module provided by PyInstaller to get the correct path of the executable. For example:

import sys
import os

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

var1 = open(os.path.join(application_path, 'pythonproject.py'), 'w')

Verify that the current working directory is set correctly when you run your executable file. You can do this using the os.chdir() function. Add error checks to handle any exceptions when opening or writing to the file. This will help you identify the problem if there are errors in file opening or writing. Try following these guidelines when writing and running your Python code and when building the executable with PyInstaller. Also, carefully check the directories and file paths to avoid path errors when transitioning from the development environment to the executable file. I hope all this helps solve your problem