Year 11 Computing — Going through a file line by line
Follow a loop that visits every line of a file in turn, turns each line into a number where it needs to, and leaves a total or a count behind.
Name: ________________________
1.The numbers saved in this file are added up as the loop meets them. What does the program print?
f = open("marks.txt", "w") f.write("8\n3\n6\n") f.close() total = 0 f = open("marks.txt", "r") for line in f: total = total + int(line) f.close() print(total)2.The file this loop is given has nothing written in it at all. What does the program print?
f = open("empty.txt", "w") f.write("") f.close() total = 0 f = open("empty.txt", "r") for line in f: total = total + int(line) f.close() print(total)3.This loop prints as it goes rather than keeping anything back. What is the last number it prints?
f = open("steps.txt", "w") f.write("3\n5\n2\n") f.close() f = open("steps.txt", "r") for line in f: print(int(line) * 10) f.close()4.A loop over an open file is written as "for line in f:". What does line hold on each trip round?
- a) One character of the file
- b) One line of the file, as a piece of writing
- c) The number of the line, counting from 0
- d) The whole file, all at once
5.This loop keeps hold of the largest number it has seen so far. What does the program print?
f = open("temps.txt", "w") f.write("14\n39\n22\n") f.close() best = 0 f = open("temps.txt", "r") for line in f: if int(line) > best: best = int(line) f.close() print(best)6.A program adds up the numbers in a file, one line at a time. Someone then adds one more line to the file, holding 5, and the program is run again without being changed. What is different?
- a) The loop makes one more trip, and the total is 1 larger
- b) The total is 5 larger, but the loop makes the same number of trips as before
- c) The loop makes one more trip, and the total is 5 larger
- d) Nothing, because the program was not changed
7.A decision inside this loop lets only some of the lines reach the counter. What does the program print?
f = open("sales.txt", "w") f.write("12\n30\n5\n22\n") f.close() big = 0 f = open("sales.txt", "r") for line in f: if int(line) > 20: big = big + 1 f.close() print(big)8.Each of these files is read line by line and its numbers added into a total. Put the files in order of the total each one gives, smallest first.
- "1\n1\n1\n1\n"
- "2\n3\n"
- "6\n8\n"
- "9\n"
Answer key — Year 11 Computing — Going through a file line by line
- 1. 17
- 2. 0
- 3. 20
- 4. b) One line of the file, as a piece of writing
- 5. 39
- 6. c) The loop makes one more trip, and the total is 5 larger
- 7. 2
- 8. 1. "1\n1\n1\n1\n" 2. "2\n3\n" 3. "9\n" 4. "6\n8\n"