how to permanently save changes into file in folder bundled while creating exe file using pyinstaller
Asked Answered
C

1

6

I have my exe application which i created with pyinstaller and bundled a folder while creating my exe which is working fine. In order to access any file from folder which i bundled while creating exe i can access those files from variable sys._MEIPASS since a temporary directory is created in Temp/_MEI96522

Now when i make a change into a file found in a folder it stays there while i am using a software but now when i close the software and open the software again the changes which i made in previous software session are gone. That file is now in its original form which it was before while bundling the folder containing the file in exe.

What i want to do is make a change into a file and needs to save the changes so that those changes stay there everytime i open the software after closing.
Is there any way to do that while keeping the folder bundled with exe.

Cleland answered 10/6, 2021 at 13:51 Comment(4)
did you have any success achieving this ? Found a workaround or anything else ? I'm currently saving things in a .json file outside the bundled exe but if theres a way to wrap everything together that would really help.Laurielaurier
No, the main problem I think is that the directory which is created is temporary and is deleted when the software is closed. So all the changes were temporary.Cleland
Thank you, I think I'll follow other solution like creating a specific folder for my application in AppData when the user launch the app for the first time.Laurielaurier
Yeah thats exactly what I did.Cleland
B
0

I found a solution to this. In order for write file to work in pyinstaller --onefile exe, it needs an absolute path. therefore, we determine the location of the running executable so we can get the dir of your exe

import sys
import os

def get_executable_dir():
    if getattr(sys, 'frozen', False):  # Check if the script is running as a standalone executable
        return os.path.dirname(sys.executable)
    else:
        return os.path.dirname(os.path.abspath(__file__))

executable_dir = get_executable_dir()

with open(os.path.join(executable_dir, "config.txt"), "w") as f:
    f.write('config content')

This code will get the absolute path of your main .exe which lets you save a config file in that same dir.

Blunder answered 29/10, 2023 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.