Revise Computingrevisecomputing.co.uk
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates

Knowledge organisers / Additional Programming Techniques

The use of basic file handling operations: Open, Read, Write, Close

All topicsPractise exam questions
Knowledge organiser

Additional Programming Techniques

2.2.3c

why you need to open and close a file as well as complete the techniques listed.

What you need to know

File handling allows programs to read data from and write data to external files. Files must be opened before they can be used and closed afterwards to ensure changes are saved. Files can be opened in read mode (to access existing data) or write mode (to save new data). This is essential for storing data permanently between program runs.

Key points

  • Files must be opened before reading or writing and closed when finished.
  • Open for reading: myFile = open("sample.txt") in OCR pseudocode.
  • Read a line: myFile.readLine() returns the next line in the file.
  • Open for writing: myFile = open("sample.txt") then myFile.writeLine("text").
  • Closing a file with myFile.close() ensures all changes are saved.
  • endOfFile() checks if the end of the file has been reached (useful in loops).
  • newFile("name.txt") creates a new empty file.
  • If a file is not closed, changes may be lost.
  • Exam Tip:A common question asks you to write a procedure that writes to a file. The procedure takes data and filename as PARAMETERS — use these parameters, don't ask for new input inside.
  • Exam Example:procedure SaveLogs(data, filename) → open(filename), writeLine(data), close(). Must use the parameters passed in.

Code examples

File handling in Python
python
# Writing to a file
f = open("scores.txt", "w")
f.write("Alice,85\n")
f.write("Bob,92\n")
f.close()

# Reading from a file
f = open("scores.txt", "r")
for line in f:
    print(line.strip())
f.close()