3

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
martineau
  • 119,623
  • 25
  • 170
  • 301
josh
  • 57
  • 1
  • 4
  • 1
    Um... `int` doesn't have a decimal point, so the error message is entirely accurate (and clear): **invalid literal for int() with base 10: '7.3'**. You can't cast a floating point value (a number with a decimal point) to an int (which doesn't accept a decimal point). – Ken White May 18 '17 at 02:15

3 Answers3

4

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)
Community
  • 1
  • 1
Eric
  • 489
  • 5
  • 16
  • 1
    Pretty good answer except you forgot to make put the list comp inside a `with open("companylist.csv", "rb") as cr:`... – martineau May 18 '17 at 02:43
  • Thanks, but now I am getting "ValueError: could not convert string to float: n/a" – josh May 18 '17 at 02:51
  • @josh what are the possible values/data types in row[2]? If you have strings are you just trying to count the rows in the file or sum the values of the column? – Eric May 18 '17 at 03:16
  • @py_noob: That's not what I meant...in fact it's not even valid syntax. – martineau May 18 '17 at 08:19
  • @josh , sorry, after some research i realized that the headers were causing the issue you mentioned above regarding the string conversion. I updated my code above. Just change the column header to the correct string value. – Eric May 18 '17 at 13:23
  • @martineau , sorry, I had wrote it in an editor and didnt compile it so i missed the error. Anyway, it's updated again and I tested it this time. – Eric May 18 '17 at 13:24
1

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
MarianD
  • 13,096
  • 12
  • 42
  • 54
0

As mentioned, cast to float instead of int.

import csv

cr = csv.reader(open("companylist.csv","rb"))
cr.next() # to skip the header 

numbers = (float(row[2]) for row in cr)
total = sum(numbers)

print total
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135