I have the following input:
ID, Last, First, Lecture, Tutorial, A1, A2, A3, A4, A5
10034567, Smith, Winston, L01, T03, 6, 5.5, 8, 10, 8.5
10045678, Lee, Bruce, L02, T05, 4.5, 6.5, 7, 7, 8.5
00305678, Obama, Jack, L01, T05, 10, 10, 9, 9.5, 10
00567890, Brown, Palin, L02, T03, 4, 7.5, 6.5, 0, 5
10012134, Harper, Ed, L01, T03, 10, 9, 7.5, 10, 6.5
10014549, Johnson, Andrew, L01, T05, 10, 0, 10, 5.5, 7
10020987, Clockwork, Milan, L02, T03, 10, 8.5, 8, 9, 9
10021234, Freeman, Skyski L01, T02, 0, 10, 10, 10, 8.5
EOF
The first line of the file explains each column of the data. Let n be the total number of students, then the next n lines of the file each corresponds to a student in the class, and contains 10 fields:
Student ID
Last name
First name
Lecture section
Tutorial sectiom
Grades for Assignments 1 (and so on...)
Assuming the grades are stored in a file grades.txt then you can read an entire line of the file into a Python string s by using the following Python statements:
file = open (‘grades.txt’, ‘r’)
s = file.readline()
You just need to open the file once, then you can use the readline() function multiple times, to read a successive line each time. After the n lines of student records, the file ends with a last line that says EOF short for End of File.
The number n is not known a priority. The sample input doesnt matter it can contain from 100 to 300 students, in a file named grades.txt We wish to eventually draw a histogram for grade distribution of Assignment 1. Therefore you need to extract the
grade of A1 for each student, by processing his/her corresponding line in the file. Construct a list that will have one entry for each student, storing his/her A1 grade. Each time you extract a new A1 grade, append it to this list.
So far this is what I've have done:
file = open('grades.txt','r')
s = file.readline()
for line in file:
newline = str(line)
grades = newline.split(",")
if len(grades)<=4:
break
elif len(grades)>5:
break
else:
grades = [float(x) for x in grades]
gradeA1 = grades[5]
print(gradeA1)
However I only get the first grade 6 and not the other A1 grades for any consecutive lines, all the A1 grades should be compiled into a list.
I have this as my edited code but I still get an error.
file = open('grades.txt','r')
s = file.readline()
for s in file:
s = file.readline()
grades = s.split(",")
if grades=='EOF\n':
break
A1grades = [float(x) for x in grades[5]]
print(A1grades)
I get an index out of range error.