I have a CSV file, here is a sample of what it looks like:
Year: Dec: Jan:
1 50 60
2 25 50
3 30 30
4 40 20
5 10 10
I know how to read the file in and print each column (for ex. - ['Year', '1', '2', '3', etc]
). But what I actually want to do is read the rows, which would be like this ['Year', 'Dec', 'Jan']
and then ['1', '50', '60']
and so on.
And then I would like to store those numbers ['1', '50', '60']
into variables so I can total them later for ex.:
Year_1 = ['50', '60']
. Then I can do sum(Year_1) = 110
.
How would I go about doing that in Python 3?
Use the csv
module:
import csv
with open("test.csv", "r") as f:
reader = csv.reader(f, delimiter="\t")
for i, line in enumerate(reader):
print 'line[{}] = {}'.format(i, line)
Output:
line[0] = ['Year:', 'Dec:', 'Jan:']
line[1] = ['1', '50', '60']
line[2] = ['2', '25', '50']
line[3] = ['3', '30', '30']
line[4] = ['4', '40', '20']
line[5] = ['5', '10', '10']