Saving Variables in Python
When you're creating your project, you may come to that point where you need to save some variables for the next launch. You may have also tried to design your own system, which you soon realise is an tedious task. But saving doesn't have to be so hard, all we need is a little bit of JSON.
What is JSON?
Before you can work on the code below, make sure that you
import json. This is in the standard library, so no extra downloads are required.
Lets get into some code!
Saving is a super simple task with JSON. We Don't have to do much work, which is the nice thing. The code can be expanded to fit your needs, but this is the basic structure you need to save a JSON file with Python.
This is super easy to use and edit, which is the nice thing. But let's look a bit closer at some of the more advanced pieces of code.
Firstly, what is
**kwargs? Well, to answer that, I'll guide you to this link which explains it better than I can here.
Secondly, what does
json.dumps() do? This is a very useful function provided by the
json module. It turns dictionaries (in this case) into JSON Objects, which looks like the JSON example at the top. As you may have noticed, Pythons dictionaries and JSONs Objects.
Loading the JSON from the file is also super simple. Again, we don't do much work, most of it is done by the
Again, it is simple to use and change. This one is even simpler than the saving, which may come a a surprise to some.
The only thing to talk is: what does
json.loads() do? So let's have a look. This is another function provided by the
json module. It takes in the string, in our case the files data, and converts it back into a dictionary. Simple as pie.
Other than my excessive use of the word "simple", you can see why this is a simple way of saving and loading variables in Python. The most complicated thing in this is probably the use of
**kwargs as most of the work was done by the
json module. Hope this helps to solve your saving and loading problems.
Have a great day!
Great informative and well written tutorial. I have not read any of your others so do not know how comprehensive they are, however have you though of a comprehensive tutorial(s) on full Python programs? Maybe a game or grabbing some data from an API and doing something with it. Keep up the good work.
Hey so like I've noticed that you're posting a lot of stuff in the Learn board. Learn is really for sharing tutorials that you make yourself. The thing you're doing here is cool and all, but try to tone it down please. Thank you