views:

370

answers:

3

I want to be able to use Python to open a .csv file like this:

5,26,42,2,1,6,6

and then perform some operation on them like addition.

total = 0
with open("file.csv") as csv_file:
        for row in csv.reader(csv_file, delimiter=','):
            for number in range(7):
                total += int(row[number]) 

The problem is that since the .csv file only has one row and an unknown number of columns, I don't know how to make this work without either hard-coding it like or using really ugly code.

Is there any way of looping through the columns using something like for columns in file in Python?

+4  A: 

You can just say

for col in row:
    total += int(col)

For example:

import csv
from StringIO import StringIO

total = 0
for row in csv.reader(StringIO("1,2,3,4")):
    for col in row:
        total += int(col)

print total    # prints 10

The reason why you can do this is that csv.reader returns a simple list for every row, so you can iterate over it as you would any other list in Python.

However, in your case, since you know that you have a file with a single line of comma-separated integers, you could make this much simpler:

line = open("ints.txt").read().split(",")
total = sum(int(i) for i in line)
Eli Courtwright
Thank you, that worked perfectly. I feel daft for not getting that :)But since I'm here I was wondering, there wouldn't happen to be a "built-in" Python function that allows you to perform some operation through out a loop? (so without having to initialize a "total" value at the beginning, I'm not really sure how it would be implemented) I ask because Python tends to simplify a lot of things.But again, thank you all for your answers. They're amazing
Baldur
reduce (http://docs.python.org/library/functions.html#reduce) does this but is frowned upon. Guido explains (http://artima.com/weblogs/viewpost.jsp?thread=98196): "apart from a few examples involving + or *, almost every time I see a reduce call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly."
Eli Courtwright
+3  A: 

You can iterate over a list of columns just as you iterate over the rows in a csv reader:

total = 0
with open("file.csv") as csv_file:
   for row in csv.reader(csv_file, delimiter=','):
        for col in row:
            total += int(col)

Or you can add the sum of each row on each pass, and skip the inside loop:

total = 0
with open("file.csv") as csv_file:
   for row in csv.reader(csv_file, delimiter=','):
        total += sum(map(int, row))

Or you can save creating an extra list by using itertools.imap instead of map.

jcdyer
A: 

i want to add some specific columns of the csv file, how can i do this?

Anand
If you have a question, please post it as a question instead of an answer.
Philipp