Teachers' Portal  /  A-Level Computer Science 9618  /  Data types and structures  /  Text files
Lesson pack · A-Level Computer Science 9618 · 10.3 · AS Level

Text files

Data that stays. Variables and arrays live in main memory and vanish when the program stops.

Student lesson Lab, full screen
At a glance

The shape of the lesson

Topic
Data types and structures
Syllabus reference
Cambridge International AS and A Level Computer Science 9618, 10.3
Level
AS Level
Duration
45 minutes, lab-led; stretches to a 60 minute block (see the contingency notes)
Position in topic
Lesson 4 of 5 in Data types and structures; follows Linear search and bubble sort; leads into Stacks, queues and linked lists
Central model
Fig. 1: lines are written to and read from a text file that remains after the program ends
Cooperative structure
Assessment
Stage 1 check and the exam-style plenary from the student lesson, plus the worksheet as the exit task
Learning objectives

By the end of the lesson, learners can

Section by section
  • Why files?: Any data that must outlive a single run of a program has to be saved somewhere other than main memory.
  • Reading a file: In the lab, run the program that writes three names to a file and then reads one back.
  • Writing and appending: WRITE starts a brand-new file every time it is opened; APPEND keeps what is there and adds to the end.
Key points to leave on the board
  • Why: variables are lost when the program ends; a file stores data permanently for later use.
  • Modes: READ, WRITE (new file, old data lost), APPEND (add to the end).
  • Read loop: WHILE NOT EOF(file), READFILE file, StringVar, process, ENDWHILE.
  • Finish: CLOSEFILE every file you opened, after the loop.
The core visual model

One picture every idea returns to

Data in variables is held in RAM and is lost when the program ends. A file is stored on secondary storage, so the data persists and can be used the next time the program runs or by another program. A text file is a sequence of lines, each read or written as a string, in order. A file is opened in one mode: READ, WRITE (creates a new file; any existing data is lost) or APPEND (adds after the existing data). Use READFILE, WRITEFILE, the EOF function and CLOSEFILE.

a text file outlives the program that wrote it Program (RAM) variables and arrays lost when it ends Names.txt AshaBenCarlos one string per line WRITEFILE READFILE modes: READ, WRITE (new file, old data lost), APPEND (add to the end) files are stored on secondary storage, so the data persists
Fig. 1: lines are written to and read from a text file that remains after the program ends
Lesson sequence

Forty-five minutes, phase by phase

TimePhaseWhat happens in the roomGrouping
0 to 5 minHook: predictOpen with the question in the title, Data that stays.. Variables and arrays live in main memory and vanish when the program stops. Put the figure on the board: it is the one picture every idea in the lesson returns to.Whole class, then pairs
5 to 13 minTeach and check: Why files?Any data that must outlive a single run of a program has to be saved somewhere other than main memory.Whole class, then pairs
13 to 21 minTeach and check: Reading a fileIn the lab, run the program that writes three names to a file and then reads one back. Project tab 6 of the lab (Writing and reading text files) and let a student drive it while the class predicts. Model the worked example Trace the read loop on the board, one line at a time. Your turn: Why is a WHILE loop used here rather than a REPEAT... UNTIL EOF("Names.txt") loop?Pairs
21 to 30 minTeach and check: Writing and appendingWRITE starts a brand-new file every time it is opened; APPEND keeps what is there and adds to the end. Model the worked example Copy without blank lines on the board, one line at a time. Your turn: A program records a new temperature in Temps.txt every hour, but the file only ever holds one reading. Suggest the cause and the fix.Connect-Extend-Challenge
30 to 36 minCheckThe four Stage 1 questions from the student lesson, answered on mini whiteboards or by show of fingers. Re-teach the one most get wrong.Individual, then whole class
36 to 43 minPlenaryThe exam-style questions from Stage 2, one at a time: thirty seconds alone, then a random call. The feedback lines in the key give the examiner's wording.Individual, random call
43 to 45 minExit and homeworkSet the worksheet below (6 questions, 23 marks). Learners self-assess against the objectives before they leave.Individual
Timing and contingency

Protect the parts that carry the learning

The sequence carries about fifty minutes of material, so the lab is driven by one student while the class predicts rather than explored freely. Times are a guide.

Protected: the check at 30 minutes. It is the only individual read on whether the key idea landed, and it is not cut.

Cut first if the build overruns: the last check in Writing and appending, never the check or the plenary.

In a 60 minute block: run worksheet questions 1 to 3 in class as a Rally Coach set and model both the hardest worked example and its check live.

Running the cooperative task

Connect-Extend-Challenge

After the new idea, each student writes three lines: how it connects to what they knew, how it extends their thinking, and what still challenges them. Pairs compare, then the challenges become the plenary.

The full structure, with its variations and the other twelve, is on the cooperative-learning page.

Examiner traps to pre-empt

What to head off, and how

Trap learners fall intoTeaching move that pre-empts it
"Files are needed to store data" is too vague.Say that variables are lost when the program ends, so the data must be stored permanently in a file to be used again later.
READFILE reads one line into a STRING variable.If a line holds a number, it is still text until it is converted, so do not declare the READFILE variable as INTEGER.
Always CLOSEFILE when you have finished.An examiner checks that every OPENFILE has a matching CLOSEFILE, with the same file name, after the loop rather than inside it.
Worksheet

Text files: worksheet

6 questions, 23 marks. Written in the style of the papers; no past paper question is reproduced.

NameClassDate
Q1 · explain[2 marks]

Explain why a program that keeps a list of high scores needs to store them in a file.

Q2 · recall[3 marks]

Describe the effect of opening a text file in each of these modes: READ, WRITE, APPEND.

Q3 · trace[4 marks]

Stock.txt contains five lines: Pen, Ink, (blank line), Pad, Pin. State the output of this pseudocode.

Count ← 0
OPENFILE "Stock.txt" FOR READ
WHILE NOT EOF("Stock.txt")
    READFILE "Stock.txt", Item
    IF Item <> "" THEN
        IF MID(Item, 1, 1) = "P" THEN
            OUTPUT Item
        ENDIF
    ELSE
        Count ← Count + 1
    ENDIF
ENDWHILE
CLOSEFILE "Stock.txt"
OUTPUT Count
Q4 · write[5 marks]

Names : ARRAY[1:30] OF STRING is a global array; unused elements hold the empty string. Write pseudocode for a procedure SaveNames() that writes every non-empty name to a new file Names.txt, one per line.

Q5 · write[6 marks]

Words.txt contains an unknown number of lines. Write pseudocode to read the lines into Words : ARRAY[1:100] OF STRING, stopping at the end of the file or when the array is full, and then output how many lines were stored.

Q6 · analysis[3 marks]

A program adds one line to Visitors.txt each time a visitor signs in. It uses OPENFILE "Visitors.txt" FOR WRITE. At the end of the day the file holds only one name. Explain why and describe how to correct the program.

Answer key and marking notes
Q1 · 2 marks
  • Variables and arrays are held in RAM and are lost when the program ends.
  • A file is held on secondary storage, so the scores are still available the next time the program runs.
Q2 · 3 marks
  • READ: data can be read from the file, starting at the first line.
  • WRITE: a new file is created for writing; any existing data in the file is lost.
  • APPEND: data is written after the existing data in the file.
Q3 · 4 marks
  • Pen is output (starts with P).
  • Ink is not output; the blank line adds 1 to Count.
  • Pad and Pin are output.
  • Final output 1 (the number of blank lines).
Q4 · 5 marks
  • PROCEDURE SaveNames() ... ENDPROCEDURE.
  • OPENFILE "Names.txt" FOR WRITE before the loop.
  • FOR Index ← 1 TO 30 ... NEXT Index.
  • IF Names[Index] <> "" THEN WRITEFILE "Names.txt", Names[Index].
  • CLOSEFILE "Names.txt" after the loop.
Q5 · 6 marks
  • Declare a counter Count ← 0 and a STRING variable for the line.
  • OPENFILE "Words.txt" FOR READ.
  • WHILE NOT EOF("Words.txt") AND Count < 100.
  • READFILE "Words.txt", LineIn, then Count ← Count + 1.
  • Words[Count] ← LineIn inside the loop, after the increment.
  • CLOSEFILE "Words.txt" and OUTPUT Count after the loop.
Q6 · 3 marks
  • Opening in WRITE mode creates a new file each time.
  • So every earlier name is lost and only the last visitor remains.
  • Open the file FOR APPEND, so each name is added after the existing lines (and close it after writing).
Quiz

6 multiple-choice questions on this lesson

From the topic question bank. Assign them in the app for a marked score in your gradebook, or run the topic as a class game.

Q11 mark

Why does a program that keeps a league table between runs need to store it in a file?

  • AVariables are held in RAM and are lost when the program ends, but a file on secondary storage persists
  • BA file can be read faster than a variable held in main memory
  • CArrays cannot hold more than one value unless they are saved to a file
  • DA program cannot output data unless it has first been written to a file
Q21 mark

Scores.txt already holds 50 lines. A program executes OPENFILE "Scores.txt" FOR WRITE. What happens to the 50 lines?

  • AThey are lost, because WRITE creates a new file
  • BThey are kept, and new lines are written after them
  • CThey are kept, and new lines are written before them
  • DThey are kept, and each new line overwrites one old line in turn
Q31 mark

Trees.txt holds six lines: Oak, Birch, Ash, Maple, Elm, Cedar. What is output?

Result ← ""
OPENFILE "Trees.txt" FOR READ
WHILE NOT EOF("Trees.txt")
    READFILE "Trees.txt", Line
    IF LENGTH(Line) > 3 THEN
        Result ← Result & RIGHT(Line, 1)
    ENDIF
ENDWHILE
CLOSEFILE "Trees.txt"
OUTPUT Result

  • Aher
  • Bkhhemr
  • CBMC
  • DBirchMapleCedar
Q41 mark

Which sequence adds the line Done to the end of the existing file Log.txt, keeping its current contents?

  • AOPENFILE "Log.txt" FOR APPEND, WRITEFILE "Log.txt", "Done", CLOSEFILE "Log.txt"
  • BOPENFILE "Log.txt" FOR WRITE, WRITEFILE "Log.txt", "Done", CLOSEFILE "Log.txt"
  • COPENFILE "Log.txt" FOR READ, WRITEFILE "Log.txt", "Done", CLOSEFILE "Log.txt"
  • DOPENFILE "Log.txt" FOR APPEND, READFILE "Log.txt", "Done", CLOSEFILE "Log.txt"
Q51 mark

A programmer reads a file with REPEAT READFILE "Data.txt", LineIn ... UNTIL EOF("Data.txt") instead of a WHILE loop. In which situation does this fail?

  • AWhen the file is empty, because a READFILE is attempted before EOF is tested
  • BWhen the file holds exactly one line, because that line is never read
  • CWhen the file holds many lines, because only the last line is read
  • DWhen the last line is blank, because EOF becomes TRUE one line early
Q61 mark

Out.txt does not exist before this pseudocode runs. What does Out.txt contain at the end?

OPENFILE "Out.txt" FOR WRITE
WRITEFILE "Out.txt", "A"
CLOSEFILE "Out.txt"
OPENFILE "Out.txt" FOR APPEND
WRITEFILE "Out.txt", "B"
CLOSEFILE "Out.txt"
OPENFILE "Out.txt" FOR WRITE
WRITEFILE "Out.txt", "C"
CLOSEFILE "Out.txt"
OPENFILE "Out.txt" FOR APPEND
WRITEFILE "Out.txt", "D"
CLOSEFILE "Out.txt"

  • ATwo lines: C, D
  • BFour lines: A, B, C, D
  • COne line: D
  • DTwo lines: A, B
Quiz key
Q1: A

RAM is volatile and a program's variables are discarded when it ends, so data needed next time must be stored permanently in a file. Reading a file is slower than reading memory, arrays hold many values without any file, and OUTPUT works directly from variables.

Q2: A

Opening a file FOR WRITE creates a new file, so any existing data in it is lost. Writing after the existing lines is APPEND mode. Text files are written sequentially, so there is no mode that inserts before old lines or overwrites them one at a time.

Q3: A

Birch, Maple and Cedar are longer than 3 characters; their last characters h, e and r are joined to give her. khhemr takes the last character of every line (as if the test were >= 3), BMC takes the first characters instead of the last, and BirchMapleCedar joins whole lines rather than one character from each.

Q4: A

APPEND keeps the existing data and WRITEFILE adds a new line after it, then the file is closed. WRITE would create a new file and lose the old lines, a file opened FOR READ cannot be written to, and READFILE reads a line into a variable rather than writing one.

Q5: A

REPEAT tests its condition after the body, so the first READFILE happens even if EOF is already TRUE: on an empty file there is no line to read. With one or more lines, the REPEAT version reads every line correctly, and a blank line is still a line, so EOF is not TRUE until it has been read.

Q6: A

The file holds A, then A, B. The second OPENFILE ... FOR WRITE creates a new file, so A and B are lost and C is written. APPEND then adds D after C, giving C, D. Four lines would need every open to keep the old data, D alone would mean APPEND also wiped the file, and A, B ignores the last four statements.

Lab and demo

What to project

The student lesson embeds these tabs. Open them full screen on the projector; every slider has a drag handle on the stage.

Slides

Slides for this lesson

A projectable deck for every pack is on the way. Until then, present the student lesson full screen: its sections, figure and lab tabs follow the same order as the plan above.

Also for this topic

Everything else you can use

Original work by the TheLucidSTEM team. The worksheet items are written in the style of the papers; no past paper question is reproduced.
Previous lessonLinear search and bubble sort