Detailed · Deep study
1Why store data in a file?
Variables and arrays are held in RAM, which is volatile, so their data is lost when the program ends. Writing the data to a file on secondary storage means it is stored permanently: it can be read the next time the program runs (e.g. high scores, settings, saved games), shared with other programs, or backed up.
2Opening, reading, writing and closing
| Command | Purpose |
|---|---|
| OPENFILE <file> FOR READ | opens a file so data can be read from it |
| OPENFILE <file> FOR WRITE | creates a new file to write to; any existing data in it is lost |
| READFILE <file>, <variable> | reads the next data item (or line of text) into the variable |
| WRITEFILE <file>, <variable> | writes the data item (or line of text) into the file |
| CLOSEFILE <file> | closes the file when it is no longer needed |
DECLARE PlayerName : STRING
DECLARE Score : INTEGER
INPUT PlayerName
INPUT Score
OPENFILE "Scores.txt" FOR WRITE
WRITEFILE "Scores.txt", PlayerName
WRITEFILE "Scores.txt", Score
CLOSEFILE "Scores.txt"OPENFILE "Scores.txt" FOR READ
READFILE "Scores.txt", PlayerName
READFILE "Scores.txt", Score
CLOSEFILE "Scores.txt"
OUTPUT PlayerName, " scored ", ScoreDECLARE LineOfText : STRING
OPENFILE "FileA.txt" FOR READ
OPENFILE "FileB.txt" FOR WRITE
READFILE "FileA.txt", LineOfText
WRITEFILE "FileB.txt", LineOfText
CLOSEFILE "FileA.txt"
CLOSEFILE "FileB.txt"f = open("Scores.txt", "w") # write mode
f.write("Ali\n")
f.write(str(25) + "\n")
f.close()
f = open("Scores.txt", "r") # read mode
name = f.readline().strip()
score = int(f.readline())
f.close()3Exam focus
Key words: file; permanent storage; OPENFILE; READ; WRITE; READFILE; WRITEFILE; CLOSEFILE.
Quick self-check
Answer in your head first, then reveal.
Data in variables is lost when the program closes (1); a file stores it permanently so it can be used again (1).
OPENFILE "Notes.txt" FOR WRITE (1); WRITEFILE "Notes.txt", Message (1); CLOSEFILE "Notes.txt" (1).
It is lost / overwritten (1).
