Here's a problem: when you write a program to read a file, you often don't know in advance how many lines it contains. It might be 4 lines today and 4,000 lines after the school adds more students next term. So you can't just write "read line 1, read line 2, read line 3" — you need a loop that keeps reading until there's nothing left to read.
The standard technique is an end-of-file flag: a boolean variable that starts as FALSE and flips to TRUE the moment the program detects it has run out of data (usually because readline() returns an empty string, meaning there was nothing left to read).
Worked Example — reading employee records
Imagine employees.txt stores four pieces of data per person, each on its own line: name, department, salary, age. So for three employees the file looks like this:
Greg
Sales
39000
43
Lucy
Human resources
26750
28
Jordan
Payroll
45000
31
To read this, we loop round four READFILE calls at a time (one per field), and check after reading the name whether it came back empty — that's our signal the file has ended:
// Pseudocode
OPENFILE "employees.txt" FOR READ
endOfFile ← FALSE
WHILE NOT endOfFile DO
READFILE "employees.txt", name
name ← TRIM(name)
READFILE "employees.txt", department
department ← TRIM(department)
READFILE "employees.txt", salary
salary ← TRIM(salary)
READFILE "employees.txt", age
age ← TRIM(age)
IF name = "" THEN
endOfFile ← TRUE
ELSE
OUTPUT "Name: " & name
OUTPUT "Department: " & department
OUTPUT "Salary: " & salary
OUTPUT "Age: " & age
OUTPUT ""
ENDIF
ENDWHILE
CLOSEFILE "employees.txt"
And the equivalent, fully working Python:
# Python
file = open("employees.txt", "r")
endOfFile = False
while not endOfFile:
name = file.readline().strip()
department = file.readline().strip()
salary = file.readline().strip()
age = file.readline().strip()
if name == "":
endOfFile = True
else:
print("Name: ", name)
print("Department: ", department)
print("Salary: ", salary)
print("Age: ", age)
print()
file.close()
Why TRIM / .strip() matters
Every line in a text file secretly ends with an invisible "newline" character (like pressing Enter). If you don't remove it, comparisons like name == "" will never come true even at the real end of the file, and printed output will have odd extra blank lines. TRIM() in pseudocode and .strip() in Python both remove this invisible character along with any extra spaces.
Practice Question
Why do we check IF name = "" to detect the end of the file, rather than checking the salary or age fields?