0

As the title says.

Is there a way to make a variable in python that "stays" even you close the file and even restart the computer? I also need to be able to access that variable anytime in the program.

The way im thinking of doing this is by making a txt file and then putting the value of the variable there, but I think its inefficient because I would need to always open the file. Moreover if the file gets deleted, then I also lost the value of that variable.

Here is some pseudocode of what I am thinking to do.

if the file does not exists:
    file = open('file.txt','w')
    x = 1
    file.write(x)

if the file exists:
    file = open('file.txt','r')
    x = file.read()

    <do stuff with the variable x>


file.close()

I want something that I can just instantly access.

P.S. I am planning to convert my python script to a .exe file using pyinstaller, hence I need the code to work even the file has been converted to .exe.

martineau
  • 119,623
  • 25
  • 170
  • 301
kalimdor18
  • 99
  • 13
  • 3
    Saving to file is how this would be done. Opening a single file is quite cheap, so I wouldn't worry about how "inefficient" it is. – Carcigenicate Sep 12 '20 at 15:59
  • 1
    Why not use environment variables and save it in .bashrc file ? – Deepak Tripathi Sep 12 '20 at 16:02
  • @DeepakTripathi can you help me to do that? i am not that good in systems yet. – kalimdor18 Sep 12 '20 at 16:24
  • There are many ways to do this and most, if not all, will involve doing file I/O. Look up variable (or object) "persistence". – martineau Sep 12 '20 at 16:34
  • all programs use some type of file to keep data between running. It can be .txt, .cfg, .xml, .json or even file with database SQLite (ie. Chrome/Firefox use SQLite to keep bookmarks and history of all visited pages). In Python you can also use `pickle` to easily keep it in file. And in all programs you can accidently delete file and lost data - but you can create backup file or you should use external backup for all files in system. – furas Sep 12 '20 at 17:17
  • if you plan to use it with `pyinstaller` then you should read how to keep files with data because pyinstaller created self-extracted .zip file with your script and Python - and when you run .exe then it create temporary folder, extract files and run it. But when you close program then it deletes folder with all files (and next time it creates this folder again). You would have to keep saved data in separated folder. – furas Sep 12 '20 at 17:20

1 Answers1

1

I saw that you want to convert it to a .exe file, so I assume that you are using windows, maybe a good option can be store in Windows regedit. Take a look in the thread How to store variables/preferences in Python for later use that I think that will help you