Skip to content
Menu

Year 10 (ages 14–15, Grade 9 in the US) · Computing · GCSE programming · Lesson 11

File handling

Reading from and writing to text files in Python: opening files in read, write and append modes, reading lines, writing lines with newline characters, closing files, and using with to close them automatically.

Exam boards: this lesson matches the Pearson Edexcel GCSE computing courses. Check which course your school follows.

Whiteboard video lesson: File handling

8-minute video lesson

Teaching, worked examples and 20 practice questions solved step by step.

Watch free for a month

What your child will learn

  • Open a file in the correct mode
  • Read lines from a text file
  • Write and append to a text file
  • Explain why files must be closed

The method

  1. open(filename, mode): "r" read, "w" write, "a" append.
  2. "w" replaces the file; "a" adds to the end.
  3. Add \n to end each line you write.
  4. Use with … as f: so the file closes automatically.

Key words: file, read mode, write mode, append mode, newline.

Worked examples

Worked examples from the lesson, with every step.

Question 1

Which mode? Add a new high score without deleting the old ones.

  1. Step 1: Keep existing data; add to it.
  2. Step 2: "a" append

Answer: append ("a")

Question 2

A file contains "Ben,67". What does this output? c:parts = line.strip().split(",") c:print(parts[1])

  1. Step 1: ["Ben", "67"]
  2. Step 2: "67"

Answer: 67

Question 3

What goes wrong? c:f = open("log.txt", "w") c:f.write("start")

  1. Step 1: File never closed.
  2. Step 2: "w" wipes old contents.

Answer: not closed; old data overwritten