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
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)
Make a garbage value and read in the first 2 values and "trash" them then when reading in the 3rd value add it to your sum. Don't forget that initially you need to ignore the first 3 values of the file since it will pick up the headers.
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
Given that 'value' is in column 2, you can perform the following simple for loop:
value_sum=0
for row in cr:
value_sum += row[2]
Or, you can use a comprehension, if you understand it:
value_sum = sum([row[2] for row in cr])