🔒
Unlock Everything
£7.99/month
or £59/year
Subscribe now →
💻 Component 2 · 2.2 Programming
2.2.1f File Handling I/O
OCR J277 · GCSE Computer Science · ~10 min read
Notes
Video
Slides
Worksheet
Quiz

Why File Handling?

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

CommandPurpose
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 = 1 TO 3
    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!
TermDefinition
🎯

Mini Test — 2.2.1f File Handling

10 questions · 10 marks · 10 minutes

← 2.2.1e Subroutines 2.2 Programming 2.3.1 Defensive Design →