Year 11 Computing — 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.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)2.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()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.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)5.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))6.A program saves some writing into a file and then reads it back. Put these five things in the order they have to happen.
- Read the lines back out
- Write the lines into it
- Open the same file again with "r"
- Close the file
- Open the file with "w"
7.A program writes one of these pieces of writing into a file and then reads it back with readlines(). Match each one to the number of lines that comes back.
- "red\n"
- "red\nblue\n"
- "red\nblue\ngreen\n"
- "red\nblue\ngreen\nblack\n"
- ""
- 1
- 3
- 0
- 4
- 2
8.Sort each of these by whether it changes what the file holds or only looks at what is there.
Groups: Changes what the file holds · Only looks at what is there
- f.write("red\n")
- f.write("9\n")
- f.readlines()
- open("notes.txt", "w")
- f.read()
- open("notes.txt", "r")
Answer key — Year 11 Computing — Writing and reading a file
- 1. 21
- 2. 2
- 3. bag
- 4. 42
- 5. 3
- 6. 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
- 7. "red\n" → 1; "red\nblue\n" → 2; "red\nblue\ngreen\n" → 3; "red\nblue\ngreen\nblack\n" → 4; "" → 0
- 8. f.write("red\n") → Changes what the file holds; f.read() → Only looks at what is there; open("notes.txt", "w") → Changes what the file holds; f.readlines() → Only looks at what is there; open("notes.txt", "r") → Only looks at what is there; f.write("9\n") → Changes what the file holds