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()
| file | mode | log.txt line 1 | line 2 | line 3 |
|---|---|---|---|---|
| open | w | (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.
Step through one line at a time and watch the file's lines on the right.
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.
Pick a task, then pick the mode you'd open the file in.
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
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?
What does the term file handling describe?
Why save program data to an external file?
Name the five key file-handling techniques.
When can a program open a file using its name alone?
What are modes r, w and a for?
Opening a file in w mode: what happens if the file already exists?
What does append mode do to an existing file?
What does readline return each time it's called?
What does readlines give you?
What data type is data copied from a text file?
What does the strip method remove?
How do you make text appear on separate lines in a file?
Why close a file when you've finished with it?
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 postedMore OCR GCSE Computer Science topics
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.