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:
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
CodePudding user response:
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)
CodePudding user response:
A more concise and arguably more Pythonic approach could be:
import csv
with open('myText.csv') as csv_:
gpas = [float(gpa) for _, gpa, _ in csv.reader(csv_)]
print(f'Average GPA is {sum(gpas)/len(gpas):.2f}')
Note:
This will fail if the file is empty or does not conform to the example shown in the original question