Python for Absolute Beginners Transcripts
Chapter: Reading and writing files in Python
Lecture: Concept: Saving JSON

Login or purchase this course to watch this video and the rest of the course contents.
0:00 You already know how to load JSON.
0:02 And it turns out it's actually
0:03 really similar to save it.
0:05 So what we have to do is start with
0:06 some object that we want to save.
0:08 And it has to be what's called
0:10 serializable or convertible in to JSON.
0:12 There' weird things that don't work
0:14 like datetimes for some reason
0:15 are not supported there.
0:16 But if you have simple stuff like
0:18 lists and numbers and strings and so on
0:20 then it's all fine.
0:21 So what we have here is we have our leaders.
0:23 And when we said load leaders we either
0:24 get an empty dictionary or one filled
0:26 out with names and then their scores.
0:28 Right?
0:29 Either way we want to save that
0:30 when we record a winner.
0:31 So we're going to go over here
0:32 and we're going to find the winner.
0:33 Increment their value.
0:34 Remember we had that test to see if
0:35 they were in there or not.
0:37 And then we got to do our file trick
0:38 again to get the full path.
0:40 Not the relative path or the short
0:42 path with no directories.
0:43 We use our width statement.
0:44 We open up a file just like before.
0:47 But the difference this time is that red W.
0:49 Instead of giving it an r for read.
0:51 We give it a w for write.
0:53 Now it's not clear from this here
0:55 but this means overwrite.
0:56 Replace.
0:57 It doesn't put it on to the end of a file.
0:59 You got to do something else for that.
1:00 And I'll talk about that later.
1:01 But for now if you want to write
1:03 completely the contents of this object
1:06 in to that file as JSON.
1:07 You're going to put a w.
1:08 And then we just go to our JSON library.
1:10 Which we've already used.
1:11 But instead of calling load
1:13 we say dump.
1:14 Boy do I wish they called that save.
1:16 Anyway, dump.
1:17 And we pass the object to be saved.
1:19 And then the file stream to save it to.
1:22 And that's it. You've now loaded up this JSON through load_leaders.
1:25 And then you've made some changes
1:26 and saved it back right here.