SLIDE 1
CSZone.co.uk
Click to reveal · Arrow keys also work
OCR J277 · Component 2 · Topic 2.2.1d

Programming Techniques
File Handling

Open, Read, Write, Close — in OCR ERL and Python

CSZone OCR GCSE Computer Science J277
Learning Objectives

By the end of this video you will be able to...

Explain why file handling is needed and name the four operations: Open, Read, Write, Close
Open a file in read or write mode and explain the difference between the two
Read data from a file using readline() and loop through an entire file using endOfFile() in OCR ERL
Write data to a file using write(), and explain that opening in write mode overwrites existing content
Write equivalent file handling code in Python, including the with statement for safe file handling
⚡ File handling lets programs save data between runs. Without it, everything is lost when the program ends.
File Handling — Overview

Why file handling — and the four operations

THE PROBLEM
Variables only store data while the program is running. When the program ends, all data is lost. File handling lets programs save data permanently to disk and load it back next time.
WITHOUT FILES
A quiz app stores the high score in a variable. Program ends → score is gone. Next run → back to zero. No persistence.
WITH FILES
The quiz app writes the score to scores.txt. Program ends → score saved. Next run → score loaded back from file. Persistent data.
THE FOUR OPERATIONS — OCR SPEC
OperationPurpose
OpenConnect the program to a file — specifying read or write mode
ReadRetrieve data from the file into the program
WriteSend data from the program out to the file
CloseDisconnect the file — saves changes and frees resources
⚡ These four operations always happen in order: OpenRead/WriteClose. You cannot read or write a file that hasn't been opened. You must always close when finished.
File Handling

Opening and closing a file — modes

OCR ERL — OPEN AND CLOSE
// Open for reading (default): myFile = open("data.txt") // Open for writing: myFile = open("data.txt", "w") // Always close when finished: myFile.close()
In OCR ERL, open() without a second argument opens in read mode by default. Pass "w" to open for writing.
FILE MODES
ModeERLEffect
readopen("f.txt")Read existing content
writeopen("f.txt","w")Creates/overwrites file
PYTHON — OPEN AND CLOSE
# Open for reading: myFile = open("data.txt", "r") myFile.close() # Open for writing: myFile = open("data.txt", "w") myFile.close() # Open for appending (add to end): myFile = open("data.txt", "a") myFile.close()
WRITE MODE WARNING
Opening a file in write mode ("w") immediately deletes all existing content — even before you write anything. If the file does not exist, it is created. Use write mode with care.
Reading Files

Reading from a file — readline()

readline()
readline() reads one line from the file and moves the read position forward. Each call returns the next line. The line includes the newline character at the end.
OCR ERL — READ ONE LINE
myFile = open("names.txt") line1 = myFile.readline() line2 = myFile.readline() print(line1) print(line2) myFile.close()
EXAMPLE FILE — names.txt
Alice Bob Charlie
First readline() → "Alice\n"  |  Second readline() → "Bob\n"
PYTHON EQUIVALENT
myFile = open("names.txt", "r") line1 = myFile.readline() line2 = myFile.readline() print(line1) print(line2) myFile.close()
PYTHON — WITH STATEMENT (RECOMMENDED)
with open("names.txt", "r") as myFile: line1 = myFile.readline() line2 = myFile.readline() print(line1) print(line2) # file closed automatically here
⚡ Python's with statement closes the file automatically when the indented block ends — even if an error occurs. This is safer than calling close() manually.
Reading Files

Reading all lines — the endOfFile() loop

THE PATTERN
To read every line in a file, use a WHILE loop that keeps reading until endOfFile() returns True. This works for files of any length — you don't need to know how many lines there are.
OCR ERL — READ ALL LINES
myFile = open("names.txt") WHILE NOT myFile.endOfFile() DO line = myFile.readline() print(line) ENDWHILE myFile.close()
HOW endOfFile() WORKS
endOfFile() returns True when the file pointer has passed the last line. The condition NOT endOfFile() means: keep looping while there are still lines to read.
PYTHON — READ ALL LINES
# Method 1: readline() in a loop with open("names.txt", "r") as myFile: line = myFile.readline() while line != "": print(line) line = myFile.readline() # Method 2: loop directly over file with open("names.txt", "r") as myFile: for line in myFile: print(line)
IN THE EXAM
Use OCR ERL for pseudocode questions — always use WHILE NOT myFile.endOfFile() DO ... ENDWHILE with readline() inside. This is the expected pattern.
Writing Files

Writing data to a file

write()
write() sends a string to the file. It does not automatically add a newline. You must add "\n" to move to a new line for the next write.
OCR ERL — WRITE TO FILE
myFile = open("output.txt", "w") myFile.write("Alice\n") myFile.write("Bob\n") myFile.write("Charlie\n") myFile.close() ← output.txt now contains 3 lines
WRITING A VARIABLE VALUE
nameinput("Enter name: ") scoreint(input("Enter score: ")) myFile = open("results.txt", "w") myFile.write(name + "\n") myFile.write(str(score) + "\n") myFile.close()
PYTHON EQUIVALENT
with open("output.txt", "w") as myFile: myFile.write("Alice\n") myFile.write("Bob\n") myFile.write("Charlie\n") # file closed automatically # Writing a number — must cast to str: score = 95 with open("results.txt", "w") as myFile: myFile.write(str(score) + "\n")
TWO IMPORTANT RULES
1. Always add "\n" to the end of each written value — without it, the next write continues on the same line.

2. You can only write strings to a file. Numbers must be cast with str() first.
File Handling

Complete OCR ERL patterns — read and write

FULL READ PATTERN — OCR ERL
// Read all lines, store in array: names ← ["", "", ""] myFile = open("names.txt") i0 WHILE NOT myFile.endOfFile() DO names[i] ← myFile.readline() ii + 1 ENDWHILE myFile.close()
This stores each line into an array element. The counter i tracks which array slot to fill next.
FULL WRITE PATTERN — OCR ERL
// Write array contents to file: names ← ["Alice", "Bob", "Charlie"] myFile = open("names.txt", "w") FOR i = 0 TO 2 myFile.write(names[i] + "\n") NEXT i myFile.close()
PYTHON — READ INTO LIST
names = [] with open("names.txt", "r") as myFile: for line in myFile: names.append(line.strip()) # .strip() removes the \n at end
PYTHON — WRITE FROM LIST
names = ["Alice", "Bob", "Charlie"] with open("names.txt", "w") as myFile: for name in names: myFile.write(name + "\n")
⚡ The .strip() method in Python removes the trailing \n from each line when reading. In OCR ERL pseudocode you don't need to worry about this — just use readline() directly.
Python File Handling

Python file handling — the with statement

WHY with IS SAFER
If you use open() and the program crashes before close(), the file may be left open and data may be lost or corrupted. The with statement guarantees the file is closed even if an error occurs.
WITHOUT with — RISKY
myFile = open("data.txt", "r") line = myFile.readline() # If an error happens here... myFile.close() ← may never reach this
WITH with — SAFE
with open("data.txt", "r") as myFile: line = myFile.readline() # If an error happens here... # file ALWAYS closed here
PYTHON FILE MODES REFERENCE
ModeMeaningCreates?
"r"Read onlyNo — error if missing
"w"Write (overwrite)Yes — creates new
"a"Append (add to end)Yes — creates new
⚡ OCR ERL uses open("f") for read and open("f","w") for write. Python adds "r" for read and "a" for append. The exam focuses on read and write — know both.
OCR ERL vs PYTHON — QUICK COMPARE
OperationOCR ERLPython
Open readopen("f")open("f","r")
Open writeopen("f","w")open("f","w")
Read linef.readline()f.readline()
End of filef.endOfFile()line == ""
Writef.write(s)f.write(s)
Worked Example

File handling — exam-style problem

PROBLEM
Write a program that reads all names from students.txt (one name per line), prints each name, then writes the message "All students loaded." to a file called log.txt.
OCR ERL SOLUTION
// Step 1 — read and print all names myFile = open("students.txt") WHILE NOT myFile.endOfFile() DO name = myFile.readline() print(name) ENDWHILE myFile.close() // Step 2 — write log message logFile = open("log.txt", "w") logFile.write("All students loaded.\n") logFile.close()
PYTHON SOLUTION
# Step 1 — read and print all names with open("students.txt", "r") as myFile: for line in myFile: print(line.strip()) # Step 2 — write log message with open("log.txt", "w") as logFile: logFile.write("All students loaded.\n")
KEY STEPS IN THIS SOLUTION
Open each file before using it — separate open for read and write
WHILE NOT endOfFile() loop reads every line regardless of how many there are
Close each file as soon as you're done with it — before opening the next
Exam Practice

File handling — exam questions

Question 1 — 1 mark
A programmer opens a file using: myFile = open("data.txt", "w")
State what happens to the existing content of data.txt.
Answer — Q1
The existing content is deleted / overwritten. Opening in write mode immediately clears all previous content — even before any write() call is made. (1 mark)
Question 2 — 2 marks
Write OCR ERL pseudocode to open a file called scores.txt, read and print every line until the end of the file, then close it.
Answer — Q2
myFile = open("scores.txt") ← [1] WHILE NOT myFile.endOfFile() DO print(myFile.readline()) ← [1] ENDWHILE myFile.close()
Mark 1: correct open and close. Mark 2: WHILE NOT endOfFile() loop with readline() inside.
Question 3 — 4 marks
Write OCR ERL pseudocode for a program that:
• asks the user to enter 3 names
• stores each name in an array
• writes all 3 names to a file called names.txt, one per line
• closes the file
Exam Answers

Question 3 — answer and mark scheme

Q3 MARK SCHEME
names ← ["", "", ""] ← [1] array declared FOR i = 0 TO 2 names[i] ← input("Enter name: ") ← [1] input into array NEXT i myFile = open("names.txt", "w") ← [1] open write mode FOR i = 0 TO 2 myFile.write(names[i] + "\n") ← [1] write + newline NEXT i myFile.close()
Also accept: inputting directly into the file without an array — 1 mark for open write mode + 1 mark per correct write line.
COMMON MARK LOSSES ON THIS Q
• Forgetting "w" in open — defaults to read mode, writing will error
• Forgetting "\n" in write — all names end up on one line
• Not calling close() — always required for full marks
PYTHON EQUIVALENT — FOR REFERENCE
names = [""] * 3 for i in range(3): names[i] = input("Enter name: ") with open("names.txt", "w") as myFile: for name in names: myFile.write(name + "\n")
THE FOUR OPERATIONS — ALWAYS IN ORDER
OPEN
READ/WRITE
CLOSE
⚡ In a 4-mark write question, examiners look for: (1) array/variable setup, (2) correct input loop, (3) open in write mode, (4) write with "\n" and close. Each is one logical step — one mark each.
Common Mistakes

Common mistakes — avoid these in the exam

MISTAKE 1 — Forgetting to close the file
Omitting myFile.close() at the end. This is nearly always a mark in the exam — and in real programs, not closing may leave data unsaved or corrupt the file
✓ Always end file handling with myFile.close() — it is an explicit OCR spec point
MISTAKE 2 — Opening in read mode then trying to write
Using open("file.txt") (default read) then calling write() — this will cause an error because the file is open in read mode
✓ To write: open("file.txt", "w") — the "w" is required
MISTAKE 3 — Forgetting "\n" when writing
Writing myFile.write("Alice") followed by myFile.write("Bob") — the file will contain "AliceBob" on one line
✓ Always append + "\n" to each write: myFile.write("Alice\n")
MISTAKE 4 — Writing a number without casting to str
Writing myFile.write(score) where score is an integer — write() only accepts strings, so this causes a TypeError
✓ Always cast numbers: myFile.write(str(score) + "\n")
Summary

Key points — 2.2.1d

File handling lets programs save data permanently. The four operations in order are: Open → Read/Write → Close. Always close the file when finished
Open modes — no second argument or "r" opens for reading; "w" opens for writing and immediately deletes existing content
Readingreadline() reads one line per call. Use WHILE NOT endOfFile() DO ... ENDWHILE to read every line in a file of unknown length
Writingwrite() accepts strings only. Always add "\n" to move to a new line. Cast numbers with str() before writing
Python — use the with open(...) as f: pattern — it closes the file automatically even if an error occurs. OCR ERL uses endOfFile(); Python checks line != ""
⚡ Next topic: 2.2.1e — String Manipulation. Concatenation, slicing, and built-in string methods.
2.2.1d Complete

File Handling
Open · Read · Write · Close

Get the full resource pack at CSZone.co.uk

📄
Marked Worksheet
CSZone.co.uk
Quiz
CSZone.co.uk
📊
Slides
CSZone.co.uk
Next Up
2.2.1e — String Manipulation