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.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.