In: Computer Science
On Python
Preview the provided sample file called studentdata.txt. It contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student.
Using the text file studentdata.txt write a program that calculates the average grade for each student, and print out the student’s name along with their average grade with two decimal places.
# open file
file = open('studentdata.txt', "r")
# read each line
for line in file:
line = line.split()
# extract name
name = line[0]
# extract scores
scores = [int(s) for s in line[1:]]
# compute average score
avg = sum(scores)/len(scores)
print("{} has average score of {:.2f}".format(name, avg))
# close file
file.close()
.
Screenshot:
.