Lesson 9 of 10
Lesson 9

File Handling

Persist data beyond the life of a program by reading from and writing to files. Understand open modes, sequential access and the importance of closing files.

35 min GCSE Level File I/O, Modes, Sequential Access
Language:

Every time you save a document, edit a spreadsheet or export a photo, a program is writing data to a file. Without file handling, every program would start fresh each time it ran - no saved games, no stored contacts, no history.

Think about it: What information in your daily apps would be lost if programs could not write to files? List three examples.
File
A named collection of data stored persistently on a disk - it survives after the program ends.
Open mode
A flag that controls how a file is accessed: read (r), write (w), or append (a).
Sequential access
Reading or writing a file from start to finish, one record or line at a time.
File pointer
An internal marker that tracks the current position in a file as it is read or written.
Append mode
Opens a file and moves the pointer to the end so new data is added without overwriting existing content.
Closing a file
Releasing the file handle so the OS can flush pending writes and make the file available to other processes.

Opening, Reading and Writing

Before you can interact with a file you must open it. The open mode determines what operations are permitted and where the file pointer starts.

The three essential modes
r - Read
Opens an existing file. Pointer starts at the beginning. Error if file does not exist.
w - Write
Creates the file if it does not exist, or overwrites it if it does. Pointer at start.
a - Append
Creates the file if it does not exist. Pointer at the end - existing content is preserved.
# --- Write a file ---
with open("scores.txt", "w") as f:
    f.write("Alice 95\n")
    f.write("Bob 82\n")
# File is automatically closed here

# --- Read the whole file ---
with open("scores.txt", "r") as f:
    contents = f.read()
    print(contents)

# --- Read line by line ---
with open("scores.txt", "r") as f:
    for line in f:
        print(line.strip())

# --- Append a new score ---
with open("scores.txt", "a") as f:
    f.write("Carol 78\n")
using System.IO;

// --- Write a file ---
File.WriteAllText("scores.txt", "Alice 95\nBob 82\n");

// --- Read the whole file ---
string contents = File.ReadAllText("scores.txt");
Console.WriteLine(contents);

// --- Read line by line ---
string[] lines = File.ReadAllLines("scores.txt");
foreach (string line in lines)
    Console.WriteLine(line);

// --- Append a new score ---
File.AppendAllText("scores.txt", "Carol 78\n");
Always close your files

Python's with statement automatically closes the file when the block ends. In C#, File.* helper methods handle opening and closing for you. If you open a file manually, always call close() / Close() - unflushed buffers can mean data is silently lost.

Reading Methods Compared

There are several ways to read from a file, each suited to a different situation:

Python methods

read()
Returns the entire file as one string.
readline()
Returns the next single line including the newline character.
readlines()
Returns a list where each element is one line.

C# equivalents

ReadAllText()
Reads the entire file into one string.
StreamReader.ReadLine()
Reads the next line from a stream.
ReadAllLines()
Returns an array of strings, one per line.
with open("data.txt", "r") as f:
    all_lines = f.readlines()     # list of strings

for line in all_lines:
    parts = line.strip().split(",")   # split CSV
    name = parts[0]
    score = int(parts[1])
string[] allLines = File.ReadAllLines("data.txt");
foreach (string line in allLines)
{
    string[] parts = line.Split(',');
    string name  = parts[0];
    int    score = int.Parse(parts[1]);
}

High Score Table

A common exam scenario: read scores from a file, find the highest, then add a new score and save the file.

# Read existing scores
scores = []
with open("scores.txt", "r") as f:
    for line in f:
        scores.append(int(line.strip()))

highest = max(scores)
print(f"Highest score: {highest}")

# Add new score
new_score = int(input("Enter your score: "))
with open("scores.txt", "a") as f:
    f.write(str(new_score) + "\n")

print("Score saved!")
// Read existing scores
int[] scores = Array.ConvertAll(
    File.ReadAllLines("scores.txt"), int.Parse);
Console.WriteLine($"Highest score: {scores.Max()}");

// Add new score
Console.Write("Enter your score: ");
string newScore = Console.ReadLine();
File.AppendAllText("scores.txt", newScore + "\n");
Console.WriteLine("Score saved!");

Simulated File I/O Sandbox

Experiment with the three file modes. The virtual disk shows you exactly what is stored after each operation.

Mode:
Input - what you want to write
Program output
Output will appear here...
Virtual disk (scores.txt)
[ empty ]

Three Quick Challenges

Predict the output

A file log.txt already contains Line 1. After running this code, how many lines does the file contain?

with open("log.txt", "w") as f:
    f.write("Line 2
")
Fill in the blank

You want to add a new score without deleting existing scores. Which mode?

with open("scores.txt", "") as f: f.write(str(score) + " ")
var sw = new StreamWriter("scores.txt", );
Spot the bug

This crashes at runtime. Why?

f = open("data.txt", "r")
f.write("hello")
f.close()

Check Your Understanding

1. A program opens a file in write mode ("w"). The file already contains data. What happens to the existing data?
Write mode (w) truncates (empties) the file before writing. Use append mode (a) to preserve existing content.
2. Which open mode should you use to add new records to the end of an existing log file without deleting earlier entries?
Append mode (a) moves the file pointer to the end so new writes are placed after all existing content.
3. What does Python's with open(...) as f: block guarantee?
The with statement is a context manager. It calls __exit__ on the file object when the block ends, which closes the file even if an exception is raised.
4. A student writes: lines = f.readlines(). What type is lines?
readlines() returns a list. Each element is a string for one line, including the newline character at the end. Use .strip() to remove it.
5. What is sequential file access?
Sequential (serial) access processes a file in order - the file pointer moves forward as each line is read. Random access (not covered at GCSE) allows jumping to any position.

Beyond the basics

A student's program reads a file in a loop and finds the average score. The file contains 1 million lines. What are two potential problems, and how could each be addressed?
Memory: Reading all 1 million lines into a list with readlines() could use a large amount of RAM. Better to iterate over the file object line by line (for line in f) so only one line is in memory at a time.

Speed: Opening and closing the file once is fine, but if the program re-opens the file repeatedly inside the loop, the OS overhead adds up. The loop should be inside a single with block.

Practice and Consolidation

Worksheet 1
File Modes Matching
Match open modes to their effects and trace what the file contains after each operation.
Download PDF
Worksheet 2
Read and Write Tasks
Write algorithms that open files, process data, and save results.
Download PDF
Worksheet 3
Exam-Style Questions
Trace file contents through multi-step programs and answer describe/explain questions.
Download PDF
Lesson 9 - Programming
File Handling
Starter activity
Show a score-tracker that stores scores in a Python list. Run it, add some scores, then exit. Ask: "Where did those scores go?" Follow up: "How could a real app remember your high score tomorrow?" Use this to motivate why persistent file storage exists before any syntax is introduced.
Lesson objectives
1
Open files in read, write and append modes and explain the difference between each.
2
Read file contents using read(), readline() and readlines().
3
Write and append text data to a file, including correct use of newline characters.
4
Explain why closing a file matters and use the with statement as best practice.
5
Distinguish between sequential and direct access file methods.
Key vocabulary
file handleopen()close()read mode "r"write mode "w"append mode "a"readline()readlines()sequential accessdirect accesspersistent datawith statement
Discussion questions
What is the difference between data stored in a variable and data stored in a file? When does each disappear?
What happens to existing content when you open a file in write mode? Why could this be dangerous in a real application?
Can you think of a real-world system that must use sequential access? What would make direct access better in that scenario?
Exit tickets
Write Python code to open a file called scores.txt in append mode and write the string "95\n" to it. [3 marks]
Explain the difference between readline() and readlines(). [2 marks]
Define "sequential file access" and give one advantage and one disadvantage compared to direct access. [3 marks]
Homework suggestion
Build a personal score logger: (1) ask the user for their name and a score, (2) append both to a file, (3) on next run, read all entries back and display them sorted from highest to lowest score. Extension: also show the average and all-time highest score.