CIE AS & A Level Computer Science, section 10.3 (Files)
Why files are needed
Variables and arrays are stored in RAM, which loses its data when the program ends or the power is off. A file stores data permanently on secondary storage, so it can be used again, shared, and processed in large amounts.
File operations in pseudocode
OPENFILE "marks.txt" FOR READ
OPENFILE "marks.txt" FOR WRITE
OPENFILE "marks.txt" FOR APPEND
| Mode | Effect |
|---|---|
READ |
the file is opened so it can be read from the start |
WRITE |
the file is opened for writing, and replaces any existing contents |
APPEND |
the file is opened and new data is added to the end |
READFILE <file>, <variable>reads the next line into a variable.WRITEFILE <file>, <text>writes a line.EOF(<file>)isTRUEwhen the end of the file has been reached.CLOSEFILE <file>closes the file (always do this).
Reading all the lines
OPENFILE "marks.txt" FOR READ
Total ← 0
WHILE NOT EOF("marks.txt")
READFILE "marks.txt", Line
Total ← Total + STR_TO_NUM(Line)
ENDWHILE
CLOSEFILE "marks.txt"
OUTPUT Total
Writing lines
OPENFILE "names.txt" FOR WRITE
WRITEFILE "names.txt", "Aisha"
WRITEFILE "names.txt", "Ben"
CLOSEFILE "names.txt"
Python
with open("names.txt", "w") as f: # write mode
f.write("Aisha\n")
f.write("Ben\n")
with open("names.txt") as f: # read mode
for line in f:
print(line.strip()) # Aisha, Ben
Common mistake: opening a file in WRITE mode when you meant to add to it. WRITE erases the existing contents; use APPEND to keep them. Also, always close the file, or the data may not be saved.
Exam tip: choose the file mode to fit the task (READ, WRITE or APPEND). Use WHILE NOT EOF(...) to read to the end, and finish with CLOSEFILE.
Check yourself
Why is a file used to store data?
Files keep data permanently on secondary storage, whereas variables in RAM are lost when the program ends.
What does opening a file in append mode do?
It keeps the existing contents and adds new data at the end.
What does `EOF` test?
Whether the end of the file has been reached.