I want to total a column in a CSV file using the python script below. However, I'm getting the following error.
invalid literal for int() with base 10: '7.3'
What is wrong with my script?
import csv
cr = csv.reader(open("companylist.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
Instead of creating the total variable and incrementing it, you can do it in one shot via a Generator Expression.
import csv
with open("book1.csv", "rb") as csv_file:
reader = csv.DictReader(csv_file)
total = sum(float(row["column_name_here"]) for row in reader)
print(total)
You are trying converting non-integer string value to int with your statement
total += int(row[2]) # possibly do other things with data/rows
use float() instead of it:
total += float(row[2]) # possibly do other things with data/rows
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