Variables store data in RAM — when a program ends, all that data is lost. File handling allows programs to read from and write to files on the hard drive, so data persists between program runs.
Examples: saving a high score, reading a list of student names, logging events.
OCR J277 File Handling Commands
Command
Purpose
open("file.txt")
Opens a file for reading and/or writing
file.readline()
Reads one line from the file
file.readLine()
Same as readline() — OCR J277 pseudocode variant
file.writeLine(data)
Writes data to the file followed by a newline
file.endOfFile()
Returns True if the end of the file has been reached
file.close()
Closes the file and saves any changes
Reading from a File
Open the file, use a WHILE loop to read lines until endOfFile() returns True, then close it.
// Read and display all lines from scores.txt
myFile = open("scores.txt") WHILE NOT myFile.endOfFile()
line = myFile.readLine() OUTPUT line END WHILE
myFile.close()
Writing to a File
Open the file (this creates it if it doesn't exist or overwrites its contents), write data, then close.
// Write three lines to output.txt
myFile = open("output.txt")
myFile.writeLine("Alice: 95")
myFile.writeLine("Bob: 82")
myFile.writeLine("Charlie: 77")
myFile.close()
Appending to a File
In OCR J277, the open command with a write mode or a specific append keyword adds new data to the end of an existing file without overwriting it.
// Append a new score to an existing file
newName = INPUT
newScore = INPUT
myFile = open("scores.txt")
myFile.writeLine(newName + ": " + str(newScore))
myFile.close()
Complete Worked Example
A program asks the user for 3 names and writes them to a file, then reads them back and displays them.
// Write 3 names to names.txt
myFile = open("names.txt") FOR i = 1TO3
name = INPUT
myFile.writeLine(name) NEXT i
myFile.close()
// Read back and display all names
myFile = open("names.txt") WHILE NOT myFile.endOfFile() OUTPUT myFile.readLine() END WHILE
myFile.close()
Why Must Files Be Closed?
Closing a file flushes the buffer — ensures all written data is saved to disk
Releases the file so other programs can access it
Prevents data corruption if the program crashes after writing
Exam tip: OCR J277 often asks you to write pseudocode to read from or write to a file. Always include: open the file, a WHILE NOT endOfFile() loop for reading, readLine() or writeLine(), and close(). Forgetting close() loses a mark. Also be ready to explain why file handling is needed (data persistence beyond program runtime).
⚠️ Common Mistakes
Forgetting to close the file — always end with myFile.close()
Using a FOR loop instead of WHILE NOT endOfFile() when you don't know how many lines the file has
Confusing readline() (reads ONE line) with reading the entire file at once
Not explaining that file handling is needed because RAM is volatile (data lost when program ends)
Confusing writeLine() (writes AND adds newline) with just writing — writeLine is the OCR J277 command
✅ Notes completed!
▶
Video coming soon
Click slide or press arrow keys to navigate
Worksheet — 2.2.1f File Handling I/O
8 questions · 26 marks
Q1Explain why file handling is needed. Why can't a program just store all data in variables?[2]
✅ Mark scheme
Variables are stored in RAM which is volatile — data is lost when the program ends or the computer is switched off [1]. File handling allows data to be stored permanently on a hard drive/secondary storage so it persists between program runs [1].
Q2State the purpose of each OCR J277 file handling command: open(), readLine(), writeLine(), endOfFile(), close().[5]
✅ Mark scheme
open() — opens a file for reading or writing [1]. readLine() — reads one line from the file [1]. writeLine(data) — writes a line of data to the file and moves to a new line [1]. endOfFile() — returns True when the last line has been read [1]. close() — closes the file and saves all changes [1].
Q3Write OCR J277 pseudocode to open a file called "students.txt" and read all lines, displaying each one on screen. Remember to close the file.[4]
✅ Mark scheme
myFile = open("students.txt") [1]; WHILE NOT myFile.endOfFile() [1]; OUTPUT myFile.readLine() [1]; END WHILE; myFile.close() [1].
Q4Write OCR J277 pseudocode to write five scores entered by the user to a file called "results.txt".[4]
✅ Mark scheme
myFile = open("results.txt") [1]; FOR i = 1 TO 5 [1]; score = INPUT; myFile.writeLine(str(score)) or myFile.writeLine(score) [1]; NEXT i; myFile.close() [1].
Q5Explain why it is important to close a file after you have finished using it. Give two reasons.[2]
✅ Mark scheme
Any 2: ensures all data written is flushed from the buffer and saved to disk [1]; releases the file so other programs can access it [1]; prevents data corruption if the program crashes [1]; good programming practice [1].
Q6Why is a WHILE NOT endOfFile() loop used when reading a file, rather than a FOR loop?[2]
✅ Mark scheme
The number of lines in a file may not be known in advance [1]. A WHILE NOT endOfFile() loop continues reading until the end of the file is reached, regardless of how many lines there are [1]. A FOR loop requires knowing the exact number of iterations beforehand.
Q7A file "log.txt" contains: "Error: line 4\nWarning: line 7\nError: line 12\n". Write pseudocode to read the file and count how many lines start with "Error". Output the count.[4]
✅ Mark scheme
count = 0 [1]; myFile = open("log.txt"); WHILE NOT myFile.endOfFile() [1]; line = myFile.readLine(); IF line.startsWith("Error") THEN count = count + 1 END IF [1]; END WHILE; myFile.close(); OUTPUT count [1]. Answer: 2.
Q8Describe what happens when a program calls open("data.txt") followed by writeLine("Hello") and then close(). Explain what each step does to the file on disk.[3]
✅ Mark scheme
open("data.txt") — opens the file (creates it if it doesn't exist, or prepares it for writing) [1]; writeLine("Hello") — writes "Hello" followed by a newline character to the file's buffer in memory [1]; close() — flushes the buffer to disk, saving "Hello\n" to data.txt, then releases the file handle [1].
?
out of 26 — self-mark above
Topic Quiz
Question 1 of 15
You scored
out of 15
Card 1 of 8
Click to reveal definition
🎉
Complete!
Term
Definition
🎯
Mini Test — 2.2.1f File Handling
10 questions · 10 marks · 10 minutes
⏱ 10:00
10 marks
Section A — Multiple Choice [5 marks]
Q1Why is file handling needed in programming?
Q2Which OCR J277 command checks if the end of a file has been reached?
Q3Which loop structure is most appropriate when reading from a file whose length is unknown?
Q4What does myFile.writeLine("Hello") do in OCR J277?
Q5What is the purpose of myFile.close() at the end of file handling code?
Section B — Short Answer [5 marks]
Q6State two reasons why you must close a file after using it in a program.
Mark schemeAny 2: ensures all data is flushed from the buffer and saved to disk [1]; releases the file so other programs/processes can access it [1]; prevents data corruption [1].
Q7Write OCR J277 pseudocode to read and display all lines from a file called "diary.txt".
Mark schememyFile = open("diary.txt") [1]; WHILE NOT myFile.endOfFile() [1]; OUTPUT myFile.readLine(); END WHILE; myFile.close() [1].
Q8Explain why a program needs file handling to save a high score in a game.
Mark schemeVariables are stored in RAM which is volatile — when the game ends, all data is lost [1]. File handling writes the high score to secondary storage (hard drive) so it is saved permanently and can be loaded the next time the game is opened [1].
Q9Write OCR J277 pseudocode to ask the user for their name and score, then write both to a file called "scores.txt" on separate lines.
Q10What does readLine() return when called on a file? What happens if you call it when endOfFile() is already True?
Mark schemereadLine() returns one line of text from the file (as a string) and advances the file pointer to the next line [1]. If called when endOfFile() is True, behaviour is undefined / may return empty string / may cause an error — this is why we check endOfFile() BEFORE calling readLine() in the WHILE loop condition [1].