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?
Step 1: In order to read rows in Python, First, we need to load the CSV file in one object. So to load the csv file into an object use open() method. Step 2: Create a reader object by passing the above-created file object to the reader function. Step 3: Use for loop on reader object to get each row.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With