You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers file handling as required by OCR J277 Section 2.3. File handling allows programs to read data from files and write data to files, so that information persists even after the program has finished running. OCR uses specific pseudocode syntax for file operations that you must know for the exam.
When a program ends, all data stored in variables is lost. File handling allows programs to:
OCR uses specific functions for file handling:
| Function | Purpose |
|---|---|
openRead(filename) | Opens a file for reading |
openWrite(filename) | Opens a file for writing (creates new or overwrites) |
readLine() | Reads the next line from the file |
writeLine(data) | Writes a line of data to the file |
close() | Closes the file |
endOfFile() | Returns true if the end of the file has been reached |
OCR Pseudocode:
myFile = openRead("students.txt")
while NOT myFile.endOfFile()
line = myFile.readLine()
print(line)
endwhile
myFile.close()
Python:
# Method 1: Using with statement (recommended)
with open("students.txt", "r") as my_file:
for line in my_file:
print(line.strip()) # strip() removes the newline character
# Method 2: Reading all lines into a list
with open("students.txt", "r") as my_file:
lines = my_file.readlines()
for line in lines:
print(line.strip())
myFile = openRead("data.txt")
firstLine = myFile.readLine()
secondLine = myFile.readLine()
print(firstLine)
print(secondLine)
myFile.close()
with open("data.txt", "r") as my_file:
first_line = my_file.readline().strip()
second_line = my_file.readline().strip()
print(first_line)
print(second_line)
OCR Exam Tip: Always remember to
close()the file after reading or writing in OCR pseudocode. In Python, using thewithstatement automatically closes the file, which is considered best practice. In the exam, if writing pseudocode, you MUST includeclose().
OCR Pseudocode:
myFile = openWrite("output.txt")
myFile.writeLine("Hello, World!")
myFile.writeLine("This is line 2")
myFile.writeLine("This is line 3")
myFile.close()
Python:
with open("output.txt", "w") as my_file:
my_file.write("Hello, World!\n")
my_file.write("This is line 2\n")
my_file.write("This is line 3\n")
When you use openWrite(), if the file already exists, its contents are completely replaced. This is important to remember — you could accidentally lose data.
OCR Pseudocode:
names = ["Alice", "Bob", "Charlie"]
scores = [150, 120, 180]
myFile = openWrite("highscores.txt")
for i = 0 to 2
myFile.writeLine(names[i] + "," + str(scores[i]))
next i
myFile.close()
print("Scores saved!")
Python:
names = ["Alice", "Bob", "Charlie"]
scores = [150, 120, 180]
with open("highscores.txt", "w") as my_file:
for i in range(3):
my_file.write(f"{names[i]},{scores[i]}\n")
print("Scores saved!")
OCR Pseudocode:
myFile = openRead("highscores.txt")
while NOT myFile.endOfFile()
line = myFile.readLine()
parts = line.split(",")
name = parts[0]
score = int(parts[1])
print(name + ": " + str(score))
endwhile
myFile.close()
Python:
with open("highscores.txt", "r") as my_file:
for line in my_file:
parts = line.strip().split(",")
name = parts[0]
score = int(parts[1])
print(f"{name}: {score}")
OCR Pseudocode:
procedure registerUser()
username = input("Choose a username: ")
password = input("Choose a password: ")
myFile = openWrite("users.txt")
myFile.writeLine(username + "," + password)
myFile.close()
print("Registration successful!")
endprocedure
function checkLogin(enteredUser, enteredPass)
myFile = openRead("users.txt")
while NOT myFile.endOfFile()
line = myFile.readLine()
parts = line.split(",")
if parts[0] == enteredUser AND parts[1] == enteredPass then
myFile.close()
return true
endif
endwhile
myFile.close()
return false
endfunction
Python:
def register_user():
username = input("Choose a username: ")
password = input("Choose a password: ")
with open("users.txt", "a") as my_file: # 'a' = append mode
my_file.write(f"{username},{password}\n")
print("Registration successful!")
def check_login(entered_user, entered_pass):
with open("users.txt", "r") as my_file:
for line in my_file:
parts = line.strip().split(",")
if parts[0] == entered_user and parts[1] == entered_pass:
return True
return False
| Operation | OCR Pseudocode | Python |
|---|---|---|
| Open for reading | openRead("file.txt") | open("file.txt", "r") |
| Open for writing | openWrite("file.txt") | open("file.txt", "w") |
| Read a line | file.readLine() | file.readline() |
| Write a line | file.writeLine(data) | file.write(data + "\n") |
| Check end of file | file.endOfFile() | Handled by for line in file |
| Close file | file.close() | file.close() or use with |
The full lifecycle of a file from open through process to close can be summarised as:
flowchart TD
A([Start]) --> B[openRead or openWrite filename]
B --> C{Reading or Writing?}
C -->|Reading| D[Loop while NOT endOfFile]
D --> E[line = readLine]
E --> F[Process line: cast, split, compare]
F --> D
C -->|Writing| G[writeLine data]
G --> H{More data?}
H -->|Yes| G
H -->|No| I[close file]
D -->|endOfFile true| I
I --> J([End])
openRead() to read and openWrite() to write.close() files after use.readLine() reads one line; writeLine() writes one line.endOfFile() checks if you have reached the end of the file.OCR Exam Tip: File handling questions on Paper 2 typically ask you to read data from a file and process it (e.g. count records, find a specific entry, calculate a total). Practise the OCR pseudocode syntax —
openRead,readLine,endOfFile, andcloseare the key functions you must know.
A school network stores login events in the text file login_log.txt. Each line contains a username followed by the number of minutes the user was logged in, separated by a comma (for example: "alice,45"). Write a program that reads this file and outputs the total minutes for a specific user.
OCR reference language pseudocode:
targetUser = input("Enter username to search: ")
totalMinutes = 0
found = false
myFile = openRead("login_log.txt")
while NOT myFile.endOfFile()
line = myFile.readLine()
parts = line.split(",")
username = parts[0]
minutes = int(parts[1])
if username == targetUser then
totalMinutes = totalMinutes + minutes
found = true
endif
endwhile
myFile.close()
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.