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().

Python 3
  1. f = open("scores.txt", "w")
  2. name = "Amy"
  3. score = 15
  4. f.write(name)
  5. f.write(score)
  6. f.write("Ben,12\n")
  7. 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 · Why use a file?

Tomorrow, where is the score?

A game program stores the player's best score in a variable: best = 42. The player quits the game, so the program ends. Tomorrow they run the game again.

Which is closest to what you think?
How sure are you?

Exam line: Say what is lost and what survives: values held only in variables are lost when the program stops; data written to a file in secondary storage persists.

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 = 15
f.write(name + "," + str(score) + "\n")
name = "Ben"
score = 12
f.write(f"{name},{score}\n")

Variables

file=(no file yet)

Step 1. Before the program runs, there is no scores.txt at all.

Step 1 of 8Called right: 0 of 2

Watch the file column. It changes only when a write() line runs, and once at line 1.

Computer Science · File modes

Write mode "w"vsAppend mode "a"

Same write() calls. Different result, because of the mode the file was opened with.

Focus

The data already in the file

Write mode "w"

Erased

Append mode "a"

Kept, all of it

The insight

This is the difference that matters. "w" is the quietly destructive one: the old contents go as soon as the file is opened for writing.

Where the new data ends up

Write mode "w"

It is all that remains: only the newly written data

Append mode "a"

On the end, after the existing contents

If the file does not exist

Write mode "w"

It is created

Append mode "a"

It is created

The mode to choose when

Write mode "w"

The old contents should be discarded and replaced

Append mode "a"

Existing data must be kept and new records added after it

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.

6 of 6 still to sort.

Read the situation, then decide what should happen to what is already in the file.

Exam line: Give the reason as well as the mode: say whether the existing records must be kept, or replaced.

Computer Science · Your turn

Write the lines yourself

A file called "league.txt" already holds records from earlier games. A program has a variable player holding a name (a string) and a variable points holding a whole number (an integer). Write the Python lines that add player and points to league.txt as a new comma-separated record on its own line, without losing the earlier records. [5 marks]

0 words · your answer stays on this page and is not sent anywhere.

Exam line: Show every piece of the record: the mode, the str() conversion, the delimiter and the "\n".

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

1Variables are lost when the program stops; a file in secondary storage keeps the data.
2write() takes only a string: convert numbers with str() and build each line with + or an f-string.
3write() adds no newline: end every record with "\n" and separate items with a delimiter such as a comma.
4Mode "w" erases the old contents and replaces them; mode "a" keeps them and adds to the end.
5A missing file is created in both modes.

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?
Values held only in variables are lost when the program stops. Data in a file in secondary storage persists after the program ends.
How do you write text to a file that is already open for writing in Python 3?
Call the file object's write() method with the text, for example f.write("Hello").
What happens if you pass an integer or a float to write()?
Python raises a TypeError, because write() accepts only a string.
How do you write a number such as score to a file?
Convert it to text first with str(), for example f.write(str(score)).
Two ways to build a line of output from several values?
Join strings with the + operator, or use an f-string. Convert any non-strings first, then write the result with a single write() call.
Does write() start a new line by itself?
No. It adds no newline, so text from consecutive calls sits directly together in the file.
How do you make each record sit on its own line?
Write "\n" at the end of each item or record.
Why put a delimiter such as a comma between items on one line?
So the items can be told apart when the file is read back later.
What does opening a file in "w" mode do to the data already in it?
It erases it. Only the newly written data remains.
What does opening a file in "a" mode do to the data already in it?
It keeps all of it and adds the new data to the end.
Which mode would you pick, "w" or "a", and how do you decide?
Ask whether existing data must be kept. If it must, with new records added after it, use "a". If the old contents should be discarded and replaced, use "w".
What happens in "w" or "a" mode if the file does not exist?
It is created.

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 Eduqas GCSE Computer Science topics

See the full Eduqas Computer Science curriculum →

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.