Read CSV Records as Lists (Solution)
And the file was named
numbers.csv. You’re going to open the file for reading. In fact, you could skip the
mode parameter because Python always opens a file for reading by default, but it never hurts to be explicit about your intent when writing code.
So far so good, but how do you actually read the CSV data from the file? This reader object is an interesting one because it doesn’t provide any method. So the only way to read the rows from a CSV file with it is by iterating over the reader object using a
01:55 In this case, you are asked to treat those values as integers. There are a couple of ways to do this, but my favorite one involves using a list comprehension, which looks somewhat similar to the standard list literal in Python.
To apply one, you must use the square bracket syntax around the list that you want to iterate over, which is this row here. Then you must define a
for loop inside the square brackets, and then at the front, you must include an expression that will be used to fill the new list.
02:34 When I save the file and run it again, the quotes around the numbers disappear, indicating they’re integer literals. Now that’s great, but instead of printing the rows, we want to add them to a list.
This means we won’t see the output anymore after running the script. So the last step will be printing all the numbers that we loaded from the CSV file. We want to call the
print() function after leaving the
with statement’s code block on the same level as the variable definition.
Become a Member to join the conversation.