0

I want to create a program, but I need a variable that doesn't reset every time I close the program. I don't know how to do it, and all the other answers I found here don't make sense to me. If anyone knows how, please let me know.

I tried these three lines of code that I got from another answer, but I don't yet know how to use it.

file = open("Saved_Variables (Python)","w")
file.write(balance)
file.close()

(I created a folder named "Saved_Variables (Python)")

  • Please provide enough code so others can better understand or reproduce the problem. – Community Jul 27 '23 at 17:21
  • 2
    You need to write data to a file, and read it back when the program starts up again., read up on "serialize" Also, you can't write to the folder itself, it needs to be a file name inside of the folder. – Dave S Jul 27 '23 at 17:21
  • Sooner or later you'll need to save more variables, and query their values, etc. so better take a look at https://docs.python.org/3/library/sqlite3.html or similar – Diego Torres Milano Jul 27 '23 at 17:27
  • you could use [Serialz (github)](https://github.com/OneMadGypsy/serialz). You tell it when to save the state of your classes, and that will be it's state every time you start your program. – OneMadGypsy Jul 27 '23 at 17:28

1 Answers1

0

You can use the pickle lib:

Example:

import pickle

balance = 1000  

file_path = 'SavedVariables.py'

with open(file_path, 'wb') as file:
    pickle.dump(balance, file)

You can read this question answered in the forum too:

Saving and loading objects and using pickle

  • 3
    For simple data such as bank balances, prefer to serialize with [json](https://docs.python.org/3/library/json.html). The output is conveniently human readable & editable. And when interpreter or library changes versions you won't be faced with a bunch of binary pickle files that are unreadable under the new version. – J_H Jul 27 '23 at 17:51