Grade 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.A program reads a file of several lines using readlines(). What does readlines() hand back?
- a) A list, with one piece of writing in it for each line of the file
- b) A dictionary, with the line numbers as its keys
- c) A number saying how many lines the file holds
- d) One long piece of writing with the whole file in it
3.What comes back from readlines() is an ordinary list, so a position can be asked for out of it. Which word does this program print?
f = open("names.txt", "w") f.write("pen\nbag\ncup\n") f.close() f = open("names.txt", "r") lines = f.readlines() f.close() print(lines[1])4.A file holds the single line 12. A program opens it, reads that line and holds on to it. What sort of thing is the program holding?
- a) A number, ready to be added to something straight away
- b) Nothing at all until the file has been closed again
- c) A piece of writing, which has to be turned into a number before it can be added to anything
- d) A list holding the digit 1 and the digit 2
5.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))6.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()7.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
- Open the same file again with "r"
- Open the file with "w"
- Read the lines back out
- Close the file
8.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))
Answer key — Grade 10 Computer Science — Writing and reading a file
- 1. 42
- 2. a) A list, with one piece of writing in it for each line of the file
- 3. bag
- 4. c) A piece of writing, which has to be turned into a number before it can be added to anything
- 5. 2
- 6. 2
- 7. 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
- 8. 3