Python file handling

Reading and writing files is a required topic in every UK GCSE Computer Science specification. This unit covers Python's file I/O API: opening a file with open(), the read/readlines/write methods, the modes 'r', 'w' and 'a', and — most importantly — using with blocks so files always close cleanly. Every example runs in the browser via RunPy's in-browser file system, so learners can see the file contents update as their code runs. Perfect for classroom teaching, GCSE and A Level revision, and independent or home-schooled learners.


What you'll learn

  • Open a file with open(filename, mode)
  • Understand the modes: 'r' (read), 'w' (write, overwrites), 'a' (append)
  • Read a whole file with .read(); line by line with .readlines() or a for loop
  • Write to a file with .write() — remember it doesn't add a newline
  • Use with open(...) as f: so the file always closes

UK GCSE topic coverage

  • File writing
  • Multi-line writing
  • File reading
  • splitlines
  • for line in f
  • File + cast + accumulate
  • with statement
  • CSV parsing
  • Append mode
  • Applied file handling

Worked example

Append a line to a log file, then read it back

with open("log.txt", "a") as f:
    f.write("New entry\n")

with open("log.txt", "r") as f:
    for line in f:
        print(line.strip())

Try a full unit free with a RunPy account

Sign up free and get the whole of Unit 1 (Input, Output and Variables) with checked tasks and instant feedback, plus a selection of the exam-style questions so you can practice on real GCSE-style content before upgrading.


Lessons in this unit

Full interactive lessons with checked tasks are available to signed-in RunPy users. Unit 1 and a selection of exam-style questions are free with a RunPy account.

  1. Writing to a file
  2. Writing several lines
  3. Reading a file
  4. Counting the lines
  5. Reading line by line
  6. Processing numbers from a file
  7. A safer way to open files: with
  8. Parsing data with .split()
  9. Adding to a file: append mode
  10. Bringing it together: a file tool

Frequently asked questions

What does the 'w' mode do to an existing file?
It overwrites it — everything already in the file is lost the moment you open it in 'w' mode. Use 'a' (append) to add to a file without wiping it.
Why use with open(...) as f?
The with block closes the file automatically when you're done, even if an error happens inside. It's the safest way to handle files and the pattern expected in GCSE exam answers.
Do I need to add \n when writing?
Yes. .write() does not add newlines for you. If you want each write on its own line, include \n at the end of the string.