CSV file parsing and averaging in Python
Contents
1 CSV file
"Last Name, First Name",Math Grade,Science Grade,English Grade
"Smith, David",90,86,100
"Nakamura, Ninja",100,70,80
"Cho, Huidae",100,100,100
"Kim, Joe",50,40,100
2 Python code
data_path = r"C:\tmp\Student Grades.csv"
f = open(data_path)
skip_lines = 1
line_count = 0
sum_math = 0
sum_science = 0
sum_english = 0
count = 0
for line in f:
# if line starts with a comma, skip this line
if line.startswith(","):
continue
line_count = line_count + 1
if line_count <= skip_lines:
continue
cols = line.split(",")
last_name = cols[0].replace('"', "").replace(" ", "")
first_name = cols[1].replace('"', "").replace(" ", "")
math = float(cols[2])
science = float(cols[3])
english = float(cols[4])
average = (math + science + english) / 3
print(f"{first_name} {last_name}'s Average Grade:", round(average, 2))
sum_math = sum_math + math
sum_science = sum_science + science
sum_english = sum_english + english
count = count + 1
f.close()
print()
print("Average Math Grade:", round(sum_math / count, 2))
print("Average Science Grade:", round(sum_science / count, 2))
print("Average English Grade:", round(sum_english / count, 2))