I have a grade.txt which consist of
Mickey,Mouse,90*
Jane,Doe,50
Minnie,Mouse,95
Donald,Duck,80
Daffy,Duck,70
Trying to read the file and split to separate the names and grades while calculating the average. I'm receiving line not defined.
def main ():
  with open('grade.txt' , 'r') as f:
    lines = f.readlines(); #reads all the line in file to lines list.
  f.close(); #closes f stream.
sum = 0; #initialised sum to store the sum of all grades.
print('Name    Grade');
print('--------------------');
for line in lines: #loops through the lines list
  str = line.split(','); #splits each line based on ','
  grade = int(str[2]); #converts string to numeric value.
  sum += grade; #adds the grade value to sum.
  print(str[0]," ",str[1]," ",grade); #prints the line read after splitting.
print('Average Grade: ',round((sum/len(lines)),1)); #prints average of all grades by rounding it to 1 place.
newdata = input('Enter firstname,lastname and grade: '); #prompts user.
with open('grade.txt', 'a') as f: #opens file in append mode.
  f.write('\n'+newdata); #writes data into file in new line.
f.close(); #closes f stream
main ()
assistance in the right direction appreciated.
The error gave
 Traceback (most recent call last):
 File "main.py", line 13, in <module>
 for line in lines: #loops through the lines list
 NameError: name 'lines' is not defined
edited code
def main ():
  with open('grades.txt' , 'r') as f:
    lines = f.readlines(); #reads all the line in file to lines list.
  sum = 0; #initialised sum to store the sum of all grades.
  print('Name    Grade');
  print('--------------------');
  for line in lines: #loops through the lines list
    str = line.split(','); #splits each line based on ','
    grade = int(str[2]); #converts string to numeric value.
    sum += grade; #adds the grade value to sum.
    print(str[0]," ",str[1]," ",grade); #prints the line read after splitting.
  print('Average Grade: ',round((sum/len(lines)),1)); #prints average of all grades by rounding it to 1 place.
newdata = input('Enter firstname,lastname and grade: '); #prompts user.
with open('grades.txt', 'a') as f: #opens file in append mode.
  f.write('\n'+newdata); #writes data into file in new line.
f.close(); #closes f stream
Thanks, I got passed the line error with indentions and removed the f.close; passing that I see my code isn't outputting the contents of the file. It's only printing newdata
 
     
    