File handling
Reading a file
Assume scores.txt already contains one score per line. A program can open a file, process its contents, then close it. ERL checks endOfFile() before reading each next line. Python can loop over the open file; with open(...) closes it automatically, even if an error occurs.
file = open("scores.txt")
WHILE NOT file.endOfFile()
line = file.readLine()
OUTPUT line
ENDWHILE
file.close()
Both examples read line by line. ERL needs an explicit close; Python's with manages closing for you.
Key terms
Writing a file
Open a file for writing, write each line, then close it. ERL uses writeLine; Python's write() does not add a new line automatically, so include \n when needed. Opening with Python mode "w" replaces existing contents. with closes the file at the end of its indented block.
file = open("scores.txt", "w")
file.writeLine("Ada,18")
file.close()
Common mistake
Forgetting the line break can join separate records together. Forgetting to close an ERL file can leave data unwritten or the file unavailable to other code.
Key terms
Why programs use files
A program's variables are held in RAM, so their values are lost when the program ends. A file is saved on secondary storage, so its data is kept between runs. A game can save its high scores, an app can remember a user's settings, and a program can work through a list of records that someone else has saved.
A program usually reads a file when it starts, then writes it back when the data changes. Every file operation follows the same order: open the file, read or write, then close it.
Key terms
Creating a file and adding to it
In ERL, newFile() creates a new, empty file. The program then opens it, writes to it and closes it. In Python, opening a file in mode "w" creates it if it doesn't exist.
newFile("log.txt")
log = open("log.txt")
log.writeLine("Started")
log.close()
To add a line to the end of a file without losing what is already there, Python opens it in mode "a" (append). Mode "w" would replace the whole file.
Exam tip
In a file algorithm, marks usually go to each step: opening the file, reading or writing in a loop, and closing it. Don't leave out the close.