Watch Me Code 2: Exam Grades

A simple example of reading and writing multiple lines of data to a file.


In [ ]:
from os import path

filename = path.join("relativefolder", "WMC2-Grades.txt")
print(filename)
# Let's input a bunch of grades and write them to a file:
count = 0

with open(filename, 'w', encoding="utf-8") as in_file:
    while True:
        grade = input("Please enter a grade or type 'q' to quit: ")
        if grade == 'q':
            break
        in_file.write(grade + "\n")
        count = count + 1
    
print("%d grades entered" % count)

with open(filename, 'r', encoding="utf-8") as out_file:
    grades = []
    for line in out_file:
        grades.append(int(line))
    average = sum(grades)/len(grades)
    print("Average is %d" % average)


relativefolder\WMC2-Grades.txt

In [16]:
# read them in
count = 0
total = 0
with open(filename,'r') as inf:
    for line in inf.readlines():
        grade = float(line)
        total = total + grade
        count = count + 1
print("Read in %s grades. Average is %.2f" % (count, total/count))


Read in 5 grades. Average is 84.00

NOTE: Show this is really persistent.

  • open wmc1.txt from outside Jupyter.
  • edit the message. Re-run the 2nd example.

In [ ]: