Python for Absolute Beginners Transcripts
Chapter: Reading and writing files in Python
Lecture: Concept: Reading JSON
0:00 Lets quickly review loading data
0:02 from a text file as JSON.
0:04 So there's actually a couple of steps involved.
0:06 We wanted to manage a global variable
0:08 so we had to say global rolls
0:10 we're going to write to that ultimately.
0:12 We need the JSON libraries
0:14 so we imported that at the top.
0:15 We also saw that the working directory
0:17 affects where Python looks for non-fully specified paths.
0:22 Right, it's just rolls out JSON as well.
0:23 It's wherever you are and if that's not
0:25 where yo expect things don't work.
0:26 So we use the os.path module to do all sorts of cool stuff.
0:31 Get the directory from a file
0:32 and then take a directory plus a file name
0:35 and join it together in a operating system independent way.
0:39 That was cool, we came up with files.
0:40 And then we wanted to use the open function
0:42 pass it the file, r to read
0:44 set the encoding, store it in a variable fin.
0:47 But we wanted to make sure we did that safely
0:48 and closed it up no matter what
0:50 so we put it in this with block into a context manager.
0:53 Whew! Now we're finally ready to load our JSON
0:55 and that's just one simple line.
0:57 So we just say json.load, give it the file stream
0:59 and boom, out comes the Python dictionary
1:01 that was stored in that file.