- [Instructor] In this self check exercise,
we'd like you to use the CSV module
that you just saw in the preceding video
to create the grades.csv file
and to write into that file the comma-separated values
that you see here in the problem statement.
Then we'd like you to read that file back in
and display it formatted in three columns
with the column names ID, Name, and Grade.
So go ahead and pause the video and give that a shot,
then come back to see the answer.
Okay, let's go ahead and do this.
We'll first import the CSV module so that we can use it
to write records into a comma-separated value file.
Next, we'll open grades.csv for writing.
Again, there is that newline equals empty string argument.
And we're going to treat this file
as the variable name grades, which we will then use
to create a comma-separated value file writer.
That writer object is then used
to invoke the writerow method once for each
of the three records of information that we are outputting.
Notice again this is a list being passed
into the writerow function.
So let's go ahead and execute that.
And now to read that data back in,
we have a separate with statement.
We're reading from the grades.csv file, open for reading.
Again, newline equals empty string to ensure
that the newline characters are handled correctly.
We print out our formatted column heads
and create a reader to read from the file grades
and we then use a for loop to read one record at a time
from that comma-separated value file.
Each of the records has three pieces of information,
so we split those off from the record
that we're currently processing
and then we format those as three columns of output.
So let's execute that, and you can see indeed the three rows
of data with the column heads as specified back here
in the problem statement.