Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSV File Handling in Python and calculating values

I am taking an introductory course in Python and am currently discovering how to handle files using Python. I have a CSV file with a few student names, their majors and GPAs
I am trying to handle the file on python to calculate and print the average of the GPAs
This is a snippet of the csv file:

Ahmed Yousry,2.99,Accounting
Amina Hamdy,2.45,Marketing
Hala Hossam,3.85,BIS
Dina Gamal,3.96,BIS
Amr Nabil,3.6,Finance

and this is the code I was trying to write:

import csv
f1 = open("myText.csv")
rowlist = csv.reader(f1)
sum = 0
for row in rowlist:
    sum += row[1]
avg = sum / 5
f1.close()
print("Average GPA is", avg)

However, I keep getting an error that the sum cannot be calculated since it is reading the GPA values as strings not integer values and I have no idea how to convert them
here is what the error message says:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\practicefiles\program12.py", line 6, in <module>
    sum += row[1]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

could someone tell me where I’m going wrong? I’ve tried casting the value as an int and it still won’t work and I don’t know what else could be done
Thank you in advance to those who help out

>Solution :

Use float() function to convert string to float type.

Try:

import csv
f1 = open("myText.csv")
rowlist = csv.reader(f1)
sum = 0
for row in rowlist:
    sum += float(row[1])
avg = sum / 5
f1.close()
print("Average GPA is", avg)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading