#100DaysOfCode in Python Transcripts
Chapter: Days 37-39: Using CSV data
Lecture: Demo: Parsing the CSV file
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
We were able to read our file as text, and that gets us really close, but it doesn't really let us work with it. And now, technically, we could do,
0:08
like a crazy bunch of string operations and parse this. But, it turns out it is entirely unnecessary. So we can import the csv module.
0:16
This is a built in in Python. I'll call this reader, and I'll say csv.DictReader. There's a couple of kind if readers. DictReader is the best one.
0:26
And you pass it this file stream. And what this thing is, is it is something that you can loop over, and every time you loop over it,
0:34
you get the values out, okay. So, let's do just something really, really quick, and, just for row in reader, and just so
0:43
you can see it working I'll print out, let's say. So if we run this, looks like it's working, and what we get is something called
0:52
an Ordered Dictionary. Doesn't matter that it's ordered, all that matters to us I can ask it for the date, or the actual mean temperatures.
0:58
Like, if just want to print out this part, I can go, because this is a dictionary, let's comment that out, I can just print here,
1:09
row.get the actual mean temperature. Great, it looks like we already got a lot of data, and we could work with it.
1:17
There's one super, super challenging problem, though. If I really want to work with this data, you very likely want to ask,
1:26
is this thing less than that other thing, right. Is this temperature less than that? So we can answer our questions.
1:32
What's the hottest day, what's the coldest day? Things like this. So, let's print out the type, right.
1:37
This is going to tell us the actual underlying data type here. Strings, everything that comes back from CSV files are strings.
1:44
Even if they look like dates, or they look like, you know, numbers or something. And so in order to actually work with these,
1:52
we're going to have to do something a little bit different. So, we're going to actually write a function
1:58
that takes this sort of raw row that we have here, and instead of just saying we're going to store the text,
2:08
we're actually going to convert the numbers to numbers, the dates to dates, things like that. So we can actually answer questions like,
2:13
is this number less than that number? Alright, the string less than or greater than is not the same thing
2:19
as numerical less than or greater than, right? Like, 100 is less than 7, for example, if those were strings, but obviously not as number.