Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading rows from a CSV file in Python

Tags:

python

csv

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?

like image 869
Goose Avatar asked Nov 17 '12 06:11

Goose


People also ask

How do I read a row from a CSV file in Python?

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.


1 Answers

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'] 
like image 75
Joel Cornett Avatar answered Oct 01 '22 11:10

Joel Cornett