This is my first post. I have a function that asks for the number of students. Then, for each student, first three lines contain the following information: Student ID, name, and number of courses taken that semester. Now, for each course, the course number, credit hour, and the percentage of scores earned by the student is listed.
def rawdata():
semester = 1
if semester == 1:
raw_file = open('raw_data.txt', 'a')
total = 0.0
total2 = 0.0
num_students = int(input('Enter number of students: '))
for student in range(num_students):
raw_file.write('Start' + '\n')
student_id = input('Enter student ID: ')
name = input('Enter Name: ')
num_classes = int(input('Enter number of courses taken: '))
raw_file.write(student_id + '\n')
raw_file.write(name + '\n')
raw_file.write(str(num_classes) + '\n')
for classes in range(num_classes):
course_number = input('Enter Course Number: ')
credits = int(input('Enter Credit Hours: '))
GPA1 = float(input('Enter percentage grade for class: '))
raw_file.write(course_number + '\n')
raw_file.write(str(credits) + '\n')
raw_file.write(str(GPA1) + '\n')
total += credits
raw_file.write('End' + '\n')
raw_file.close()
print('Data has been written')
All the data is listed to a txt file and now I need to PULL this information from my raw_data.txt which looks like(varies with inputs):
Start
eh2727
Josh D
2
MAT3000
4
95.0
COM3000
4
90.0
End
Start
ah2718
Mary J
1
ENG3010
4
100.0
End
and process it so that I can calculate each students GPA. I have each students block of info contained by a Start/End and I don’t know how to read this info in my processing function in order for me to calculate their GPA. This is what I have so far:
def process():
data = open('raw_data.txt', 'r')
results = open('process_results.txt', 'w')
buffer = []
for line in data:
if line.startswith('Start'):
buffer = []
buffer.append(line)
if line.startswith("End"):
for outline in buffer:
results.write(outline)
This simply writes it all into my results text and I don’t know how to individually process each block of information to calculate the GPA. Any help would be greatly appreciated.
Since it is your own code writing out the data to the .txt file, you might consider writing it in an easier and/or more fault tolerant format for machine reading, for example JSON or XML. Alternatively, you might want to consider using pickle or cpickle to serialize the data and read it in again.
Anyway, on to your question: how to read the file. Unfortunately, you do not tell us what you want to do with the parsed data. I assume here you want to print it. Normally you would of course create a nice class or classes describing students and courses.
For parsing of files like yours, I use the string method split() a lot. split() is your best friend. See the python docs for more info on string methods.