Add all values in a CSV column in Python

后端 未结 4 1217
不知归路
不知归路 2021-01-19 23:11

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
         


        
4条回答
  •  心在旅途
    2021-01-19 23:42

    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)

提交回复
热议问题