Example: Tracing a scores report program
Most programs that use files do three things: open a file, move text between the file and variables, and close the file. In this example you trace a short Python program that reads quiz scores from one text file and writes a summary to another. For each part, predict what the file operations produce before you reveal the solution.
A teacher stores quiz scores in a CSV-style file named scores.txt. Every line, including the last, ends with a newline character \n:
Ava,82
Ben,75
Chen,91
Dana,68The program is:
records = []
total = 0
with open("scores.txt", "r") as infile:
for line in infile:
name, score = line.strip().split(",")
records.append((name, int(score)))
total += int(score)
average = total / len(records)
with open("results.txt", "w") as outfile:
outfile.write(f"Average: {average:.1f}\n")
for name, score in records:
if score >= average:
outfile.write(f"{name} {score}\n")a) What value does average hold after the reading block finishes?
Calling open("scores.txt", "r") returns a file object, the connection through which the program reads or writes the file; the name infile refers to it. Looping over a file object yields one line at a time as a string, and each string still ends with its \n.
For the first line, line is "Ava,82\n". The strip() call removes the newline, and split(",") returns the two strings "Ava" and "82". Everything read from a text file arrives as a string, so int(score) converts "82" to the integer 82 before it is stored and added to the total.
The loop body runs ________, once per line, so len(records) is 4. Adding the four scores gives a total of ________:
The division then gives
In Python the / operator always produces a float, so average holds 79.0.
b) Write out the exact contents of results.txt and count its characters, counting each newline as one character.
The second argument of open() is the file mode, which states what the program may do with the file. Mode "w" opens the file for writing, creating it if it does not exist and erasing its contents if it does. The write method adds no newline of its own, so every line ends only where the program writes \n explicitly.
The header uses the format {average:.1f}, which shows 79.0 with one decimal place. The text Average: 79.0 has 13 characters, and its newline brings the header to ________.
The loop then compares each score with 79.0:
- Ava, 82: since 82 is at least 79.0, the program writes Ava 82 and a newline, 7 characters.
- Ben, 75: below the average, so nothing is written.
- Chen, 91: the program writes Chen 91 and a newline, ________.
- Dana, 68: below the average, so nothing is written.
The file therefore holds three lines, in this order:
- Average: 79.0
- Ava 82
- Chen 91
The character count is 14 + 7 + 8 = 29 characters. Without the \n in each string, the same text would run together on one line as Average: 79.0Ava 82Chen 91.
c) Suppose the second open() uses mode "a" instead of "w", and the program runs twice, starting with no results.txt on the disk. How many lines does results.txt hold after the second run?
Mode "a" (append) creates a missing file, keeps any existing contents, and adds every write to the end of the file.
- Run 1: the file does not exist, so mode "a" creates it, and the program writes the same ________ as in part b.
- Run 2: the file now exists, so its three lines are kept and the program adds another three after them.
After the second run the file holds 3 + 3 = 6 lines, with the average header appearing twice. With the original mode "w", the second run would erase the first run's output as the file opened, leaving only 3 lines.
A student runs the Python code below. Put the events that happen while it runs into the order in which they occur, from first to last.
with open("notes.txt", "a") as f:
f.write("Lab 3 done\n")
print("saved")1.
The word saved appears on the screen.
2.
open() finds notes.txt, creating it if it does not exist, and sets writing to start after any existing text.
3.
The file object returned by open() is bound to the name f.
4.
Leaving the with block flushes the buffer to the file and closes it.
5.
f.write() hands the text Lab 3 done and a newline to the file object's buffer.
A Python program imports observations from a text file. An exception handler is a block that responds to a specified error. Complete the descriptions with the most specific built-in exception class names that Python raises.
- The program opens an input file using mode "r". The specified file does not exist, although its parent directory exists and is accessible. The most specific built-in exception class that Python raises here is .
- A different input file opens successfully with encoding="utf-8" and errors="strict". Calling read() encounters bytes that are invalid in UTF-8. At that call, read() raises the specific built-in exception .