#100DaysOfCode in Python Transcripts
Chapter: Days 37-39: Using CSV data
Lecture: Concepts: CSV programming
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Recall there were two basic steps
0:02
that we had to go through to work with this CSV data,
0:05
and they were both pretty simple.
0:06
We're going to start by importing the csv
0:09
module, so that will let us actually create
0:11
this dictionary reader to run through it,
0:14
and we're going to open a file stream
0:16
that we hand to the dictionary reader
0:18
to actually get the data.
0:21
Then we just create one of these dictionary readers
0:24
based on the file,
0:25
and gives us this thing that we can loop over
0:28
and each item that comes out of the loop
0:31
is going to be one of those rows in there.
0:34
And we get this row back and we work with it one at a time.
0:37
Now you saw the data's always text,
0:39
so you may need to upgrade it to something more usable
0:43
if you're working with numbers and dates
0:44
and things that are not just plain text.
0:47
The other thing that makes this really, really nice,
0:49
makes a big difference in terms of working with this data,
0:52
is to give it a little more structure,
0:55
and we saw that we could really easily use
0:58
something called a namedtuple.
1:01
This comes out of the collections
1:02
and then we're going to create the namedtuple here
1:06
and we call it whatever you want,
1:08
we make up the name. I said I'm going to call it record, so record it is.
1:11
Just remember it appears in two places,
1:13
and in that second part, we actually put the
1:17
basically the header from the CSV,
1:19
it just so happens that format works perfectly there.
1:22
And then we can, if we have some data,
1:24
we can create one of the by setting the keyword values.
1:27
So we set all the values there.
1:29
We actually have a shorter way to do it
1:31
if the dictionary exactly matches the items,
1:33
which it does in this case.
1:34
So we could use the **row,
1:37
because often there's a ton of keyword values to set,
1:40
and this will just do it in a super, nice shortcut here.