Not sure how to actually save data in a Python program

I’m brand new-- still learning Python. One simple thing I’m unclear on is how to save data.

For instance, if I go in the Python interpreter, define a variable, close the interpreter, and reopen the interpreter, that variable will no longer be defined.

An example of something I’d like to do is write a simple program to manage my budget-- so I’d want to be able to input info about how much I’ve spent or made, and have the program retain that info going forward. I think I know how to write the program itself, but I don’t know how to make it persist once I’ve closed out. How do I do that?

It’s actually quite easy, but there is a bit to learn in getting started.

with open("path/file.mime", flag) as file:
    # read ...

DOCS

7. Input and Output — Python 3.12.0 documentation

Aside

Definitely read as much as you can find in the aim of learning all the in’s and out’s, any gotcha’s, best practice (like using with), and general overall usage and cautions.

In my old PHP days if my script that interacted with the data was small, I planted a copy with the data, in all the data store locations. Being local it had direct access to the data files without having to traverse directories. Python is script and could be made to work the same way, but I would leave this approach to try later. For now, put the data with the script location.

 script.py
 file.mime

The above ‘with’ example could have the ‘path/’ removed. The script has direct access to the data file.

One giant caution is data protection. Create a backup of any data file before you open it for writing. If we mistakenly obliterate the file we can always restore it. Unlike our local system which can undo file deletion, open has no undo feature.

3 Likes