Class 10 Computer Science — Writing and reading a file
Follow a program that saves writing into a file and reads it back, and work out what the file holds at each point.
Name: ________________________
1.What is read back out of this file is turned into a number before it is used. What does the program print?
f = open("score.txt", "w") f.write("40") f.close() f = open("score.txt", "r") text = f.read() f.close() print(int(text) + 2)2.The number saved here is read back and used in a sum. What does the program print?
f = open("count.txt", "w") f.write("7") f.close() f = open("count.txt", "r") n = int(f.read()) f.close() print(n * 3)3.A program reads a file of several lines using readlines(). What does readlines() hand back?
- a) One long piece of writing with the whole file in it
- b) A dictionary, with the line numbers as its keys
- c) A list, with one piece of writing in it for each line of the file
- d) A number saying how many lines the file holds
4.The same file is opened for writing twice here, and each opening writes something different. How many lines does the file hold when this program has finished?
f = open("log.txt", "w") f.write("first\n") f.close() f = open("log.txt", "w") f.write("red\nblue\n") f.close()5.A file already holds several lines. A program opens it with "w" and then closes it again without writing anything at all. What does the file hold now?
- a) Everything it held before, with a blank line added on the end
- b) Nothing at all
- c) Everything it held before, since nothing was written
- d) One blank line where the writing used to be
6.Two separate writes go into one opening of the file here. What does the program print?
f = open("list.txt", "w") f.write("red\n") f.write("blue\n") f.close() f = open("list.txt", "r") lines = f.readlines() f.close() print(len(lines))7.This program saves three pieces of writing and then reads them back as a list. What does it print?
f = open("shades.txt", "w") f.write("red\ngreen\nblue\n") f.close() f = open("shades.txt", "r") lines = f.readlines() f.close() print(len(lines))8.A program saves some writing into a file and then reads it back. Put these five things in the order they have to happen.
- Write the lines into it
- Close the file
- Open the same file again with "r"
- Open the file with "w"
- Read the lines back out
Answer key — Class 10 Computer Science — Writing and reading a file
- 1. 42
- 2. 21
- 3. c) A list, with one piece of writing in it for each line of the file
- 4. 2
- 5. b) Nothing at all
- 6. 2
- 7. 3
- 8. 1. Open the file with "w" 2. Write the lines into it 3. Close the file 4. Open the same file again with "r" 5. Read the lines back out