KS4

📁 File Handling

Learn how to read from and write to files, allowing your programs to save and load data.

What you'll learn:

  • How to open and close files safely
  • Reading data from text files
  • Writing data to text files
  • Using the 'with' statement for safe file handling
  • Processing CSV data

Learning Path

Follow these activities in order.

Key Vocabulary

file

A collection of data stored on disk with a name and extension (e.g., data.txt).

open()

Function to access a file. Takes filename and mode ('r', 'w', 'a').

read mode ('r')

Opens file to read data. File must exist.

write mode ('w')

Opens file to write data. Creates file or overwrites existing.

append mode ('a')

Opens file to add data at the end. Creates file if needed.

with statement

Automatically closes the file when done. Best practice!

Quick Reference

file_handling_examples.py
# Reading a whole file
with open("data.txt", "r") as file:
    content = file.read()
    print(content)

# Reading line by line
with open("data.txt", "r") as file:
    for line in file:
        print(line.strip())

# Reading all lines into a list
with open("data.txt", "r") as file:
    lines = file.readlines()

# Writing to a file (overwrites)
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("Second line\n")

# Appending to a file (adds to end)
with open("log.txt", "a") as file:
    file.write("New entry\n")

# File modes:
# "r" - read (default)
# "w" - write (overwrites file)
# "a" - append (adds to end)
# "r+" - read and write

Exam Tips

Common Exam Questions

  • Trace what happens to file contents
  • Identify the correct file mode to use
  • Explain why 'with' is preferred
  • Debug file handling code

Common Mistakes

  • Forgetting to close files (use 'with'!)
  • Using 'w' when you meant 'a' (loses data)
  • Forgetting newline characters \n
  • Not stripping whitespace from lines