GCSE · Computer Science · Eduqas · Spec C500QS
File handling: write to a file
Your program ends and every variable vanishes. Files keep your data, but two quiet slips can wreck a file without a single warning.
Computer Science · File handling
Break it, read it, fix it
scores.txt should end up holding two records, Amy,15 and Ben,12, each on its own line. Run the program and read what comes back. Then fix line 5, run it again, and keep going until the file is right.
Line 1 opens scores.txt for writing and line 7 closes it. This lesson is about what goes inside write().
- f = open("scores.txt", "w")
- name = "Amy"
- score = 15
- f.write(name)
- f.write(score)
- f.write("Ben,12\n")
- f.close()
The error messages and the Output (the text stored in scores.txt after each run) come from running this exact code in Python 3.
Computer Science · Tracing a file
What is in the file now?
Same program, two starting files
Pick a starting situation, then call what the file holds before the table shows it. Nothing is run: every value is the lesson's. In the file, \n stands for the newline character.
f = open("scores.txt", "w")name = "Amy"score = 15f.write(name + "," + str(score) + "\n")name = "Ben"score = 12f.write(f"{name},{score}\n")
Variables
Step 1. Before the program runs, there is no scores.txt at all.
Watch the file column. It changes only when a write() line runs, and once at line 1.
Computer Science · Choosing a mode
Which mode would you open it with?
Pick a situation, then pick the mode that fits it.
Still to sort
Open with "w" (0)
The old contents should be discarded and replaced.
Where the line is: Nothing in the file needs to survive this run.
Open with "a" (0)
Existing data must be kept, with new records added after it.
Where the line is: Something already in the file must still be there afterwards.
Read the situation, then decide what should happen to what is already in the file.
WHAT YOU'VE LEARNED
A quick recap of today's lesson.
write() puts into the file exactly what you give it. Nothing more.
What you need to know
- Values held only in variables are lost when the program stops. Data written to a file in secondary storage persists after the program ends.
- In Python 3, once a file is open for writing, f.write("Hello") puts that text into it.
- write() accepts only a string. Hand it an integer or a float and you get a TypeError.
- Turn a number into text with str() before writing it: f.write(str(score)).
Have a goDev swears f.write(score) is fine "because print(score) works". Score holds the integer 15. Which one line would actually run?
f.write(str(score))
write() accepts only a string, so a bare number raises a TypeError. str() turns the 15 into the text "15" first.
- Build a whole line by joining strings with + (or an f-string), converting numbers first. Then write it with one write() call.
- write() never adds a newline. Two write() calls put their text directly next to each other in the file.
Have a goTwo calls run in a row: f.write("Amy") then f.write("Ben"). What exactly is in the file afterwards?
AmyBen, all on one line.
write() adds no newline or gap by itself, so the second text sits directly against the first.
- Write "\n" at the end of each item or record, so each one is stored on its own line.
- Items sharing a line need a delimiter, such as a comma, so you can tell them apart when the file is read back later.
- Mode "w" replaces the file: old contents are erased and only the new data remains (a missing file is created). Use it to discard and replace.
- Mode "a" adds new data to the end and keeps what is there (a missing file is created). Use it when old records must stay.
Have a goA file holds 3 records. Run A opens it in "w", Run B in "a", and each run writes one new record. Which run leaves just 1 record in the file?
Run A, the one that used "w".
"w" erases the old contents when the file is opened, so only the new record remains. "a" keeps all 3 and adds a fourth after them.
The big picture
Writing to a file keeps data after the program ends. write() takes only a string and adds no newline, so convert numbers with str(), separate items with a delimiter, and end each record with "\n". Mode "w" replaces the old contents; mode "a" keeps them and adds to the end.
Key points
Worked example
Problem
The open file f should hold one record per line in the form item,quantity, for example pen,3. A program has item = "pen" (a string) and quantity = 3 (an integer). Write the single write() line that stores this record.
⚠ Watch out
Treating write() like print(): handing it a number (a TypeError) or expecting it to start a new line by itself (the next record runs on from the last one).
Memory hook
Strings in, newline yourself: write() only eats text, and it never starts a new line for you. And remember: w wipes, a adds.
Check yourself
Cover the page. Say what is wrong with f.write(name + "," + score), then what is still wrong with f.write(name + "," + str(score)) if you want one record per line.
Flashcards
(12)Why write data to a file instead of keeping it in a variable?
How do you write text to a file that is already open for writing in Python 3?
What happens if you pass an integer or a float to write()?
How do you write a number such as score to a file?
Two ways to build a line of output from several values?
Does write() start a new line by itself?
How do you make each record sit on its own line?
Why put a delimiter such as a comma between items on one line?
What does opening a file in "w" mode do to the data already in it?
What does opening a file in "a" mode do to the data already in it?
Which mode would you pick, "w" or "a", and how do you decide?
What happens in "w" or "a" mode if the file does not exist?
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 Eduqas GCSE Computer Science topics
- Decomposition
- Designing a testing strategy
- Explaining test outcomes
- File handling: open a file
- File handling: read into a variable
- File handling: read into an array
- Iteration: condition and counter controlled loops
- Lists, tuples and dictionaries
- Mathematical and logical operations in code
- Modular structuring with abstraction
- Presenting test outcomes with commentary
- Program a solution to requirements
How this lesson was checked. This Eduqas GCSE Computer Science (specification C500QS)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 16 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.