Load Scores (Solution)
00:00
I have this source data with player scores already open on the left and saved to a local file named scores.csv
. Because this file is located in my current working directory, I won’t have to specify the full path in Python in order to open it, just the filename. By the way, if you haven’t downloaded this file yet, then you can do so now or copy and paste the corresponding values from the slides, as there are only a dozen or so rows in that file.
00:30
Over on the right, I have an empty Python module named challenge.py
, where I’ll be writing my solution. The first step is to load the data on the left into Python, so I’ll need the usual set of imports—that is, the csv
module that will allow me to read and write CSV files, as well as pathlib
’s Path
object for manipulating file paths.
00:53
As I mentioned, the CSV file depicted on the left is located in the same directory as my Python module, so I can provide the filename scores.csv
without specifying the complete path to it.
01:07
This is the input file. Because later I’ll need to define yet another path for the output file, I’ll assign this one to a variable named scores_path
, which is slightly more descriptive than just path
that I’ve been using in the review exercises before.
01:24
Next, I’m going to open that file for reading using the with
statement, explicitly setting the character encoding and disabling the universal newline translation.
01:41
Now because the CSV file contains a headline, I’ll use DictReader
and let it infer the column names from the first row. Otherwise, I’d have to take care of it manually.
01:54
To read the rows from the file, which are dictionaries, I’ll iterate over the reader object using a for
loop,
02:03 and I’ll print each row.
02:07
Let’s save and run this file. Now, as you can see, the reader object successfully translated each row in the CSV file into a Python dictionary with name
and score
as keys.
02:19 Notice that the score values, just like all other values in the CSV format, are represented as strings, so I’ll need to make sure to convert them to integers.
02:30
Let me assign those values to local variables in the loop’s body. First, name
is equal to row_dict["name"]
. Then the corresponding score is equal to row_dict["score"]
, and I’ll need to pass that to the built-in int()
function.
02:53 Okay, now I have the name of a player and the numeric score of that player at a given time. The next step is to find the highest score of all players and keep them in a leaderboard that will dump into another CSV file.
Become a Member to join the conversation.