A-Level Computer Science / Unit 10: Organising Data in Programs

10.3.1 Creating and Appending Text Files

🔒 Lesson slides are available to signed-in users. Sign in

10.3.1 Creating and Appending Text Files

Variables and arrays hold data while a program is running. A text file allows selected information to remain available after the program finishes. This section develops the pseudocode needed to create a fresh text file and to add new lines to an existing file.

By the end of this section, you should be able to:

  • Explain why a program may need persistent storage.
  • Describe a text file as a sequence of character-based lines.
  • Distinguish between WRITE and APPEND mode.
  • Use OPENFILE, WRITEFILE and CLOSEFILE correctly.
  • Write one or several lines to a text file.
  • Select a suitable file mode for a given problem.

Why Programs Need Files

Data stored in ordinary variables or arrays is normally available only while the program is executing. When the program ends, that working data is no longer available unless it has been saved somewhere persistent.

Consider a makerspace program that records equipment inspections. The inspection result must still exist tomorrow, after the computer has been restarted. A text file can preserve each completed inspection as a line.

Storage location Typical lifetime Example
Variable or array Usually only during the current program run The inspection note currently being entered
File Remains available after the program closes A saved history of completed inspections
Persistent storage: storage that keeps data after the program that created or changed the data has stopped.
Exam tip: When explaining why a file is needed, contrast temporary working data with information that must be available in a later program run.

What Is Stored in a Text File?

A text file stores characters arranged into lines. Each call to WRITEFILE writes one string as one line of the file.

InspectionLog.txt
Laser cutter | passed
Soldering station | cable replaced
3D printer | nozzle cleaned
Feature Meaning
Filename Identifies the file, for example "InspectionLog.txt".
Line One sequence of characters stored between line boundaries.
Text value The STRING written by a WRITEFILE statement.
Common misconception: A text file does not automatically preserve the data type of each value. The saved content is text. A later program may need to interpret that text before using it as a number, date or Boolean value.

Choosing Between WRITE and APPEND

The mode supplied to OPENFILE determines what should happen to the file's existing contents.

Mode Use it when... Effect on existing content
WRITE The program must create a fresh version of the file. Previous contents are replaced.
APPEND The program must preserve earlier lines and add new data at the end. Previous contents remain.
File mode: the operation requested when a file is opened, such as creating fresh output or adding to existing output.
Common mistake: Opening a valuable log file in WRITE mode can remove its earlier contents. Choose the mode before opening the file.

Creating a Fresh Text File with WRITE

A program that produces a new daily summary should start with a clean file. The file is opened in WRITE mode, one or more lines are written, and the file is closed.

DECLARE SummaryLine : STRING

SummaryLine ← "Workshop checks completed: 14"

OPENFILE "DailySummary.txt" FOR WRITE
WRITEFILE "DailySummary.txt", SummaryLine
CLOSEFILE "DailySummary.txt"

Resulting file

DailySummary.txt
Workshop checks completed: 14
Use WRITE when the new output is intended to replace the previous version, such as a report that is regenerated from current data.

Adding a New Line with APPEND

A historical log should normally preserve its earlier entries. Opening the file in APPEND mode places newly written lines after the existing content.

File before the program runs

InspectionLog.txt
Laser cutter | passed
Soldering station | cable replaced

Pseudocode

DECLARE NewEntry : STRING

NewEntry ← "3D printer | nozzle cleaned"

OPENFILE "InspectionLog.txt" FOR APPEND
WRITEFILE "InspectionLog.txt", NewEntry
CLOSEFILE "InspectionLog.txt"

File after the program runs

InspectionLog.txt
Laser cutter | passed
Soldering station | cable replaced
3D printer | nozzle cleaned
Append: add new data after the file's current contents without replacing the existing lines.

The Required Sequence: Open, Write, Close

File operations should follow a clear sequence. The file must be opened in the required mode before data are written, and it should be closed after the final write.

Stage Example statement Purpose
1. Open OPENFILE "InspectionLog.txt" FOR APPEND Makes the file available in the selected mode.
2. Write WRITEFILE "InspectionLog.txt", NewEntry Sends one line of text to the open file.
3. Close CLOSEFILE "InspectionLog.txt" Finishes access to the file and releases it.
Common mistake: Do not write to a file before it has been opened, and do not close it before all required lines have been written.
Keep the filename exactly consistent in all three statements. A small spelling difference refers to a different file.

Writing Several Lines

Once a file is open, several WRITEFILE statements may be used before it is closed. Each statement writes one line.

OPENFILE "ShiftReport.txt" FOR WRITE

WRITEFILE "ShiftReport.txt", "Morning workshop report"
WRITEFILE "ShiftReport.txt", "Safety checks: complete"
WRITEFILE "ShiftReport.txt", "Machines unavailable: 2"

CLOSEFILE "ShiftReport.txt"

Writing an array to a text file

A loop can write one array element per line. The array itself is still temporary; the resulting file is persistent.

DECLARE MachineName : ARRAY[1:4] OF STRING
DECLARE Index : INTEGER

OPENFILE "MachineList.txt" FOR WRITE

FOR Index ← 1 TO 4
    WRITEFILE "MachineList.txt", MachineName[Index]
NEXT Index

CLOSEFILE "MachineList.txt"
The file should normally be opened once before the loop and closed once after the loop.
Opening the file in WRITE mode inside the loop could repeatedly replace the file, leaving only the final line.

Choosing the Correct Mode

Requirement Mode Reason
Regenerate today's room-status report WRITE The new report should replace yesterday's version.
Add a new fault to a maintenance history APPEND Earlier faults must remain in the file.
Export the current contents of an array WRITE The file should represent the array's current state.
Add today's attendance note to a year-long log APPEND The file is a growing sequence of entries.
Base the decision on what should happen to earlier content. “Save data” alone is not enough to distinguish the two modes.

Interactive: Text File Mode Simulator

Select WRITE or APPEND, enter a new line, and step through opening, writing and closing the file. The preview shows exactly when previous content is replaced or preserved.

File before execution

EquipmentLog.txt


New line to write
Current stage Ready
OPENFILE "EquipmentLog.txt" FOR WRITE
File during / after execution

EquipmentLog.txt


Mode WRITE
File state Closed
Lines stored 2

Press Start / restart to begin the file-operation sequence.

Common Mistakes and Misconceptions

  • Using WRITE when earlier file contents must be preserved.
  • Assuming APPEND inserts data at the beginning of the file.
  • Calling WRITEFILE before OPENFILE.
  • Forgetting to close the file after writing.
  • Using inconsistent filenames across the open, write and close statements.
  • Opening a file in WRITE mode repeatedly inside a loop.
  • Assuming that a text file automatically stores numbers as numeric data types.
  • Using READ or EOF logic on this page; those belong in 10.3.2.

Practice

Task 1: Select the mode

Choose WRITE or APPEND and justify each decision.

  1. Create a fresh weekly stock summary.
  2. Add a new temperature alert to an existing history.
  3. Replace an old list of active users with the current list.
  4. Add one new delivery event to a tracking log.

Task 2: Complete the pseudocode

Write pseudocode that adds the string stored in NewMessage to the end of "SystemEvents.txt".

  1. Open the file in the correct mode.
  2. Write the value of NewMessage.
  3. Close the file.

Task 3: Write several lines

VisitorName is an array declared from index 5 to index 12.

  1. Write pseudocode to create "Visitors.txt".
  2. Use a loop to write one visitor name per line.
  3. Explain why the file should be opened before the loop.

Task 4: Diagnose the error

FOR Index ← 1 TO 6
    OPENFILE "Results.txt" FOR WRITE
    WRITEFILE "Results.txt", Result[Index]
    CLOSEFILE "Results.txt"
NEXT Index
  1. Predict what is likely to remain in the file.
  2. Rewrite the pseudocode so that all six lines are stored.

Review

Question Strong answer should include
Why is a file needed? To keep data available after the program finishes.
What does WRITE mode do? Starts a fresh file or replaces the previous contents.
What does APPEND mode do? Preserves existing lines and adds new lines at the end.
What is the correct operation sequence? Open the file, write the required line or lines, then close it.
How is an array saved one item per line? Open once, use a loop containing WRITEFILE, then close once.
What is covered next? Opening a file for reading, processing several lines and testing for EOF.
Final exam tip: Identify the required effect on existing data before choosing the mode. Then check that the same filename appears in a complete open–write–close sequence.