Turn a program off and everything it was holding in memory vanishes. So how does a game remember your high score next week, or a register keep last term's marks? The answer is files — data written to disk so it survives long after the program closes.
Memory vs the disk
Think of memory as a whiteboard and a file as a notebook. Whatever you scribble on the whiteboard is wiped the moment you leave the room (the program ends). Write it in the notebook and it is still there tomorrow. Programs constantly copy data from notebook to whiteboard (reading) and back again (writing).
The three-step dance: open, use, close
Working with a file always follows the same rhythm. You open it in a mode, you read or write, then you close it so the data is safely saved and the file is freed for others.
| Mode | Purpose |
|---|---|
| Read ("r") | Open an existing file to read its contents |
| Write ("w") | Create/overwrite a file with new contents |
| Append ("a") | Add to the end, keeping what is already there |
Records and fields
Structured text files store one record per line — all the data about one thing, such as one pupil. Each record is split into fields by a separator, usually a comma (a CSV file). So Aisha,72 is one record with two fields: a name and a mark.
open "marks.txt" for read
while not end of file
line = readline() # "Aisha,72"
parts = line.split(",") # ["Aisha","72"]
name = parts[0]
mark = parts[1]
print(name + " scored " + mark)
endwhile
close file
Read each line, split it into fields on the comma, then use each field.("w") when you meant to add to it. Write mode overwrites the whole file, destroying the old contents. Use append mode ("a") to keep existing data and add to the end.Tip: always close a file when you are done. Data written to a file may sit in a buffer and only be fully saved when the file is closed — forget to close it and you can lose the last records.