Check out a free preview of the full Practical Guide to Python course
The "Working with Files Practice" Lesson is part of the full, Practical Guide to Python course featured in this preview video. Here's what you'd learn in this lesson:
Nina walks the students through the working with Files practice.
Transcript from the "Working with Files Practice" Lesson
[00:00:00]
>> So, let's try a short exercise where we work with files and then we will practice loops and our list comprehensions and working with files. If you have the course website open, you can download this file called cities.JSON and let's take a look at it. Just has the top five cities and their populations.
[00:00:33]
So we're going to import the JSON module, which is built into the standard library in Python, and we're gonna use that to help us parse the data. I'm just going to exit my repo here and get this file. So now if I list here, I should see the file in my directory called cities.JSON.
[00:01:07]
And I'm going to open my REPL again. So if I want to work with JSON and the JSON library in Python, I need to import it. It's not a built in. And then I wanna use a context manager to open this file, so I'm gonna use that with keyword and say, with open("cities.JSON") And I'm gonna use another keyword called as, to give this open file a name, so that I can reference it later on.
[00:01:45]
So I'm gonna say as cities_file. And then I can go ahead, while I'm in this context manager, notice that I have tabbed into it. So all of the code that is indented under this statement belongs to the context manager. Anything that is after it that is not indented, is not going to get run in the scope of the context manager.
[00:02:09]
So I wanna do my stuff with the file in the context manager and then exit that block when I'm done. So I can say that the city's data is JSON.load. The city is found. And then I can print this out. And I'm gonna hit enter one more time cuz now I'm done with this file.
[00:02:40]
If I take a look at the type of city's data, we'll see that it's a list. If I take a look at the zeroth element, we'll see that it's a dictionary. So what this has returned is a list of dictionaries that matches to the JSON file, and then I can work with it.
[00:03:00]
I could use that pretty print function from earlier, so from pprint import ppprint to then pprint(cities_data). pprint in a more human readable format.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops