GCSE · Computer Science · OCR · Spec J277

File handling: open, read, write, close

One letter. That's the difference between adding today's score to your saved file and wiping every score you've ever saved. Let's make sure you pick the right one.

Computer Science · File handling

Watch the file change

This is Python. Other languages spell these commands differently, but the jobs are the same: open, write, append, read, close.

Before you step past line 7: what will log.txt hold when the program ends?

1 log = open("log.txt", "w")
2 log.write("Mon: 3 laps\nTue: 5 laps\n")
3 log.close()
4 log = open("log.txt", "a")
5 log.write("Wed: 4 laps\n")
6 log.close()
7 log = open("log.txt", "w")
8 log.write("Thu: 6 laps\n")
9 log.close()
10 log = open("log.txt", "r")
11 print(log.read())
12 log.close()
filemodelog.txt line 1line 2line 3
openw(empty)

Output

 

Step 1: Write mode creates a new file called log.txt. The program finds it by name alone because it sits in the same folder as the program. Stored anywhere else, you'd need its full path.

1 / 12

Step through one line at a time and watch the file's lines on the right.

Step 1 of 12: Write mode creates a new file called log.txt. The program finds it by name alone because it sits in the same folder as the program. Stored anywhere else, you'd need its full path..

Watch out: Line 7 looks almost the same as line 4. One letter is different, and that letter wipes three lines.

Which do you believe?

What happened to the old scores?

scores.txt holds last week's high scores. Jaz runs one line: f = open("scores.txt", "w"). She hasn't written anything yet.

What has happened to last week's scores?
How sure are you?

Your call

r, w or a?

Which mode should the file be opened in for each task?

Still to sort

r: read (0)

Only reading what's already in the file.

w: write (0)

Only writing, into a new file.

Where the line is: w and a both put data into a file. w starts the file again (overwriting any existing one); a keeps what's there and adds to the end.

a: append (0)

Adding to the end of an existing file.

6 of 6 still to sort.

Pick a task, then pick the mode you'd open the file in.

Four ways to read

Build the reading grid

The file is already open in r mode. Tick every property each reading technique has, then check.

read
readline
readlines
a for loop over the file

Find the bug

Ten bonus points that never arrive

This Python program should read a player's score from scores.txt and add 10 bonus points. One line stops it working as intended. Which one?

Ravi's program — which line goes wrong?

WHAT YOU'VE LEARNED

A quick recap of today's lesson.

One letter decides whether your file grows or gets wiped. Watch it happen.

What you need to know

  • A file is a collection of data stored digitally, identified by a name. File handling is how programs work with those files.
  • Saving program data to an external file means it can be reused when the program runs again.
  • The key file-handling techniques: open, read, write, append and close.
  • Open the file first. By name alone, it must be in the same location as the program; otherwise include its full path.
  • The mode sets the job: r is only for reading, w only for writing, and a adds to an existing file (a for append).
  • Opening in w creates a new file. If one with that name already exists, it's overwritten. Only reading? Use r.
  • Have a goPriya's diary.txt has 200 lines. She opens it with mode w, writes one new line, then closes it. How many lines are in diary.txt now?

    Just 1.

    Opening in w overwrote the existing file, so all 200 old lines were erased before her one line went in. Mode a would have kept them.

  • \n is the new line character. It puts text on separate lines, and one write statement can write several lines.
  • Have a goHow many lines will this put in the file? f.write("cat\ndog\nfox\n")

    Three: cat, dog and fox, each on its own line.

    Every \n is a new line character, so each word ends its own line. It's still only one write statement.

  • read gets the contents of the file. readline returns the next line each time it's called. readlines puts each line in a list.
  • Have a gocolours.txt has four lines: red, green, blue, pink. You call readline three times. What does the third call give you?

    blue

    Each call returns the next line rather than starting from the top again: red, then green, then blue.

  • Data copied from a file is held as a string. strip removes the new line character; casting to an integer lets you use it as a number.
  • Close the file when you're finished: it frees up system resources and protects the data. Some IDEs only write the text on close.

The big picture

A file is a collection of data stored digitally under a name, and saving program data to a file lets you reuse it next time the program runs. You open a file in a mode: r only reads, w only writes and a appends. Opening an existing file in w overwrites it, so use a to add and r to only read. read, readline and readlines (or a for loop) get data out; what comes back is a string, so strip the new line character and cast it before using it as a number. Close the file when you're done.

Key points

1File handling covers open, read, write, append and close.
2Pick the mode when you open: r reads, w writes a new file, a adds to the end.
3w overwrites an existing file with the same name; a adds to the end without erasing.
4If a file isn't in the same location as the program, include its full path.
5Use \n to start a new line inside the file.
6File data is a string: strip it, cast it, then use it.
7Always close the file at the end.

Worked example

Problem

marks.txt holds three lines: 12, 8 and 15. Write a Python program that reads every line, adds the numbers up and prints the total.

⚠ Watch out

Opening a file in w mode when you meant to add to it. It feels right, because you're writing. But w overwrites an existing file, so everything already in it is lost. To add to the end, open it with a.

🧠

Memory hook

r reads, w wipes, a adds. Choose the letter before you type the file name.

✓

Check yourself

names.txt already holds three names. Which mode adds Zara to the end, which mode would wipe the three names, and what must the program do once it's finished with the file?

Flashcards

(14)
What is a file?
A collection of data stored digitally, identified by a name.
What does the term file handling describe?
How programs work with the files that are stored on a computer.
Why save program data to an external file?
So the data can be reused when the program runs again.
Name the five key file-handling techniques.
Open, read, write, append and close.
When can a program open a file using its name alone?
When the file is stored in the same location as the program. Otherwise the full path must be included.
What are modes r, w and a for?
r is only for reading, w is only for writing, and a is for adding to an existing file (append).
Opening a file in w mode: what happens if the file already exists?
It is overwritten. A new file is created with that name, erasing what was there.
What does append mode do to an existing file?
Adds new data to the end without erasing the existing contents.
What does readline return each time it's called?
The next line in the text file.
What does readlines give you?
A list, with each line of the text file as an item.
What data type is data copied from a text file?
A string. Cast it, for example to an integer, to use it as a number.
What does the strip method remove?
Leading and trailing whitespace, including the new line character at the end of a line.
How do you make text appear on separate lines in a file?
Use the new line character, \n. Several lines can go in one write statement.
Why close a file when you've finished with it?
It frees up system resources and protects the data in the file. In some IDEs, the text isn't written until the file is closed.

Tap any card to flip it, or use Study as deck to go through them one at a time. In the full lesson these run as a spaced-repetition deck — you rate each card Hard, Good or Easy and the tricky ones keep coming back until they stick.

Learning with Lightbulb is opening soon

You can use this lesson now. Join the waitlist and we'll let you know when the full Lightbulb experience is ready.

Keep me posted

More OCR GCSE Computer Science topics

See the full OCR Computer Science curriculum →

How this lesson was checked. This OCR GCSE Computer Science (specification J277)lesson was published through Lightbulb Learning's human-designed editorial process — the educational standards, accuracy rules and publication checks it must pass were authored and approved by Philip Halpin. It passed subject-specific assessment, automated educational checks and technical publication verification before going live (publication checks completed 3 November 2026). Published pages are monitored, human spot-checking is ongoing across the lesson library, and anything found wrong is corrected or withdrawn. How our lessons are made and checked. Spotted a mistake? Email hello@lightbulblearning.co and we'll review it.