Class 10 Computer Science — 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 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)2.The numbers out of this file are collected into a list as they are read. What does the program print?
f = open("data.txt", "w") f.write("6\n11\n4\n") f.close() values = [] f = open("data.txt", "r") for line in f: values.append(int(line)) f.close() print(values[1])3.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.
- "2\n3\n"
- "9\n"
- "1\n1\n1\n1\n"
- "6\n8\n"
4.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)5.Only some of these lines reach the total. What does the program print?
f = open("takings.txt", "w") f.write("5\n40\n8\n30\n") f.close() total = 0 f = open("takings.txt", "r") for line in f: if int(line) >= 30: total = total + int(line) f.close() print(total)6.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) The number of the line, counting from 0
- c) The whole file, all at once
- d) One line of the file, as a piece of writing
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.A program opens a file, goes through it with a line loop, and closes it again. Sort each of these lines of code by how often it runs.
Groups: Runs once, outside the loop · Runs once for every line in the file
- print(int(line) * 2)
- total = total + int(line)
- f.close()
- total = 0
- f = open("data.txt", "r")
- print(total)
Answer key — Class 10 Computer Science — Going through a file line by line
- 1. 0
- 2. 11
- 3. 1. "1\n1\n1\n1\n" 2. "2\n3\n" 3. "9\n" 4. "6\n8\n"
- 4. 17
- 5. 70
- 6. d) One line of the file, as a piece of writing
- 7. 2
- 8. f = open("data.txt", "r") → Runs once, outside the loop; total = 0 → Runs once, outside the loop; total = total + int(line) → Runs once for every line in the file; print(int(line) * 2) → Runs once for every line in the file; f.close() → Runs once, outside the loop; print(total) → Runs once, outside the loop