These seems like something very simple, but search as I might I just can't get past it.
I have a CSV file like this:
Day,Event,Value
1,"Rent",500
7,"Wage Payments",1000
I wish to add up all of the numbers in the 'value' column. So far, my code is this:
cr = csv.reader(open("file.csv","rb"))
for row in cr:
print row
#print sum(Value)
How could I go about summing that value?
Thank you.
Considering the first line of csv
file is 'Day,Event,Value'
, you can use a generator expression
with sum()
>>> cr = csv.reader(open("file.csv","rb"))
>>> cr.next()
>>> print sum(int(x[2]) for x in cr)
1500
cr = csv.reader(open("file.csv","rb"))
cr.next() # to skip the header
total = 0
for row in cr:
total += int(row[2])
# possibly do other things with data/rows
print total
There are more terse ways (e.g., list comprehension, or generator expressions) to do this, but this provides the basic idea and also lets you do other things with each line as needed (as pointed out by @MarkRansom too)
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