[8.3.1-2] File Handling

[8.3.1–2] File Handling: Why Programs Read and Write Files

Why store data in files?

When a program ends, any data stored only in variables disappears from main memory. Files provide persistent storage so that information can be kept and reused later by the same program or a different one. Common examples include saving a game, keeping a class register, logging sensor readings, or loading configuration settings. You will learn how to open a file in a suitable mode, read and write either single data items or whole lines of text, and then close the file correctly.

In the IGCSE context you should be comfortable with simple text files. Text files store characters (letters, digits, punctuation, control characters like newline). Programs can read and write either one item at a time (for example a number or a word) or a whole line of text. You must also understand the difference between read, write, and append access.

Open → Process → Close: the standard pattern

  1. Open the file with a mode: read (existing data), write (create or overwrite), or append (add to the end).
  2. Process the data: read single items or lines, or write single items or lines.
  3. Close the file to free the resource and ensure all data is saved (flushed to disk).

Key terms and ideas

Term Meaning (IGCSE context) Example
Path Location of a file in the file system. "data/scores.txt"
Mode How a file is opened: read, write, or append. Read existing data; Write creates or overwrites; Append adds to end.
Record/Line One logical row of text ending with a newline character. "Amina,78" followed by newline
EOF End Of File: the point where no more data is available to read. Loops stop when EOF is reached.

Reading: single items vs whole lines

Programs may read a single item (for example the next number) or an entire line of text and then split it into fields. Reading lines is flexible because each line can contain multiple items separated by spaces or commas. The choice depends on the problem you are solving and the format of the file.

Single item: Open for reading, extract the next token as an item (for example a number), and continue until the required count is read or EOF is reached. Useful for files that store one value per line or simple streams of numbers.

Whole line: Read the full line as a string, then optionally split it into parts (for example by commas). Useful for names with spaces, or multiple fields on one line such as name, score.

EOF and empty lines: Stop processing when there is no line to read. Treat an empty string as a valid but blank line; decide whether to skip it or keep it according to your algorithm.

Writing: creating, overwriting, and appending

Choose the write mode carefully. Writing in create/overwrite mode replaces the old file completely. Appending adds to the end without removing existing content. Always close the file to ensure that all text is saved correctly.

Single item: Convert the value to text if needed and output it to the file. For numbers, also decide whether you want a newline after the item.

Line of text: Build a string that contains the fields you want, then write it and include a newline so that each record appears on a separate line when read later.

Append vs overwrite: Append preserves all existing content and adds new lines at the end. Overwrite discards the old file and starts again from empty. Use append for logs and history, overwrite for fresh reports.

Practical scenarios

Open a new file for writing, output each name followed by a newline, then close. Reopen the file for reading to verify by printing each line.

Each line contains two fields, such as Sam,72. Read a line, split it, convert the score to a number, and add to a running total. Count how many scores you read and compute the average. Handle blank lines by skipping them.

If a file cannot be opened for reading, your program should show a helpful message and avoid crashing. When writing, check that you have permission to create the file and that the path is valid. Always close any file that was successfully opened, even if an error occurs later.

Deep Dive: Newlines, buffering, and encoding

Newline characters mark the end of a line and may differ between systems, but you can treat them conceptually as a single marker that separates records. Buffering means that the system may hold data in memory before writing it to disk; closing the file ensures everything is saved. Encoding describes how characters are stored as bytes. For IGCSE tasks you can assume a standard encoding for plain English text, but remember that non-ASCII symbols may not display correctly if you mix encodings.

Copy-ready examples (CAIE pseudocode and Python)

// CAIE Pseudocode: Read lines until EOF and show them
DECLARE line : STRING
OPENFILE "notes.txt" FOR READ
WHILE NOT EOF("notes.txt") DO
    line ← READLINE("notes.txt")
    OUTPUT line
ENDWHILE
CLOSEFILE "notes.txt"

// Write three lines (overwrites any existing file)
OPENFILE "names.txt" FOR WRITE
WRITELINE("names.txt", "Amina")
WRITELINE("names.txt", "George")
WRITELINE("names.txt", "Kai")
CLOSEFILE "names.txt"
# Python: Read lines and write lines (text mode)
# Read all lines
with open("notes.txt", "r") as f:
    for line in f:
        print(line.rstrip())

# Overwrite with three names
with open("names.txt", "w") as f:
    f.write("Amina
")
    f.write("George
")
    f.write("Kai
")

# Append one more name
with open("names.txt", "a") as f:
    f.write("Zoe
")

 Key Takeaways

  • Files provide persistent storage; variables do not survive when a program finishes.
  • Follow the Open → Process → Close pattern every time you use files.
  • Choose modes carefully: read for existing data, write to create or overwrite, append to add to the end.
  • Read either single items or whole lines of text, depending on the file format and your task.
  • Handle EOF and empty lines safely to avoid errors and incorrect results.
  • Always close files so that buffered data is saved and resources are released.