Python for Absolute Beginners Transcripts
Chapter: Reading and writing files in Python
Lecture: Concept: Saving JSON
0:00 You already know how to load JSON. And it turns out it's actually really similar to save it. So what we have to do is start with
0:07 some object that we want to save. And it has to be what's called serializable or convertible in to JSON. There' weird things that don't work
0:15 like datetimes for some reason are not supported there. But if you have simple stuff like lists and numbers and strings and so on then it's all fine.
0:22 So what we have here is we have our leaders. And when we said load leaders we either get an empty dictionary or one filled
0:27 out with names and then their scores. Right? Either way we want to save that when we record a winner. So we're going to go over here
0:33 and we're going to find the winner. Increment their value. Remember we had that test to see if they were in there or not.
0:38 And then we got to do our file trick again to get the full path. Not the relative path or the short path with no directories.
0:44 We use our width statement. We open up a file just like before. But the difference this time is that red W. Instead of giving it an r for read.
0:52 We give it a w for write. Now it's not clear from this here but this means overwrite. Replace. It doesn't put it on to the end of a file.
1:00 You got to do something else for that. And I'll talk about that later. But for now if you want to write completely the contents of this object
1:07 in to that file as JSON. You're going to put a w. And then we just go to our JSON library. Which we've already used. But instead of calling load
1:14 we say dump. Boy do I wish they called that save. Anyway, dump. And we pass the object to be saved. And then the file stream to save it to.
1:23 And that's it. You've now loaded up this JSON through load_leaders. And then you've made some changes and saved it back right here.