I/O Points 0 / 30
I/O Rank Resource Leaker

Topic 2.2.7: File Handling

Open, Read, Write, Close & Data Persistence.

1 [3 Marks]
myFile = open("class_list.txt") while NOT myFile.___________(): studentName = myFile.___________() print(studentName) endwhile myFile.___________()
Fill blanks (OCR Reference Language).
✅ Mark Scheme
  • endOfFile
  • readLine
  • close
Score:
2 [2 Marks]
Why is it essential to close a file after using it?
✅ Mark Scheme

To free up memory/resources, save data physically to disk, or prevent file corruption/locks.

Score:
3 [2 Marks]
# File contains "100" score = file.readLine() total = score + score print(total)
Output? Explanation?
✅ Mark Scheme

Output: 100100

Reason: Data read from file is a String. + concatenates instead of adding.

Score:
4 [3 Marks]
01 file = open("prices.txt") 02 while NOT file.endOfFile(): 03 price = file.readLine() 04 newPrice = price * 1.2 05 print(newPrice) 06 endwhile 07 file.close()
(a) Line 04 has a Logic/Type error. Fix it.
(b) Identify minor syntax issues in Line 02 if strict ERL.
✅ Mark Scheme

(a) Fix: newPrice = float(price) * 1.2 (Must cast string to float).

(b) Syntax: endOfFile() usually needs brackets in ERL methods.

Score:
5 [4 Marks]
File data.txt: 5, 2, 8.
Trace Algorithm:
478: x = 0
479: while NOT f.endOfFile():
480:   val = int(f.readLine())
481:   if val > 4: x = x + val
482:   else: x = x - val
483: print(x)

Trace Table:

valxOutput
✅ Mark Scheme
  • Val 5 (>4) -> x = 5
  • Val 2 (<=4) -> x = 3 (5 - 2)
  • Val 8 (>4) -> x = 11 (3 + 8)
  • Output: 11
Score:
6 [6 Marks]
Read maths_scores.txt.
If score >= 50, write it to pass_list.txt.
Close both.
✅ Mark Scheme
527: f1 = open("maths_scores.txt")
528: f2 = newFile("pass_list.txt")
529: while NOT f1.endOfFile()
530:   line = f1.readLine()
531:   score = int(line)
532:   if score >= 50:
533:     f2.writeLine(line)
534: f1.close()
535: f2.close()
Score:
7 [2 Marks]
file = open("diary.txt") # Defaults to Write file.writeLine(entry)
Previous entries disappear.
(a) Why?
(b) Fix (use Append).
✅ Mark Scheme

(a) "Write" mode creates a new file / overwrites existing data.

(b) open("diary.txt", "a") (Append mode).

Score:
8 [2 Marks]
Write a check to prevent crash if file is missing.
✅ Mark Scheme

if exists("maths_scores.txt") then ...

OR TRY ... EXCEPT block.

Score: