In python, we don't normally do this using print statements. Consider the following alternative. Using a "context manager" allows you to write more than one line, and also helps avoid certain problems if the program throws an error while writing to the file.
with open('results.txt', 'a') as f:
line = "Average Grade " + str(average), "At least 70% " + str(Grade1), "60% - 69% " + str(Grade2), "50% - 59% " + str(Grade3), "40% - 49% " + str(Grade4), "Less than 40% " + str(Grade5), "Highest Grade " + str(max_grade), "Student Name:" + str(student_name)
f.write(line)
Incidentally, if you are doing this interactively, you may not see data written to the file instantly- this can be a real point of confusion when using a terminal instead of running a script! What happens is that python writes data to the file in large blocks, rather than asking the hard drive to do work every time f.write
is called. flush
ing the output buffer tells python to write the data immediately- eg f.flush()
.
The print statement actually does have a flush
argument, which may be highly relevant for that reason. Still, I would recommend using a with
statement instead.