Software Design & Development · Implementation

SDD12 — File Handling: Writing

📅 Tue 18 Aug 2026 · P3 (single)
~50 minutes
Learning intentions
Success criteria
Warm up — recap from SDD11
Answer all three questions, then check your answers.
Question 1
Which mode, passed as open()'s second argument, opens a file for reading?
Question 2
A CSV line is split with split(","). What data type is every individual field in the result, before any further conversion?
Question 3
Why does reading a CSV file usually require split() to be called twice?

Key vocabulary

Write mode ("w")
Opens a file for writing. If the file already exists, its entire existing content is erased first.
Append mode ("a")
Opens a file for writing, adding new data to the end of any existing content, without erasing it.
.write()
Writes a given string to an open file exactly as given — it does not automatically add a newline character.
Type casting
Explicitly converting a value from one data type to another, e.g. str() converting an integer to a string.
CSV formatting
Joining field values with commas, and separate records with newline characters, to produce valid CSV text.

Writing data to a file

Opening a file for writing

SDD11 covered reading; this lesson covers the reverse — sending a program's data out to a file so it persists after the program ends. Opening a file for writing uses the same open() function met in SDD11, but with a different mode. "w" (write) mode opens a file ready to receive new content — critically, if the file already exists, opening it in "w" mode immediately erases everything already in it, before a single new character is written. "a" (append) mode instead opens the file and positions any new writing at the very end of the existing content, leaving what was already there untouched.

Choosing between write mode and append mode

The choice between "w" and "a" depends entirely on intent. Use "w" when a file should be replaced completely with fresh data — for example, regenerating a whole CSV file from scratch after every item's stock has changed. Use "a" when new data should be added on top of what's already saved — for example, adding a single new item to an existing tuck shop stock list without disturbing the items already stored there. Choosing the wrong mode is a serious, silent bug: using "w" when "a" was intended destroys existing data with no warning or error.

Writing with .write()

.write(text) sends exactly the string given to it to the open file — nothing more, nothing less. Unlike Python's print(), .write() does not automatically add a newline character after the text it writes. Writing several separate pieces of text one after another with .write(), without manually including "\n" at the end of each one, joins them all together on a single line with no separation at all.

Rebuilding CSV formatting on the way out

Just as reading a CSV file needed split() applied twice (SDD11), writing one requires the reverse: joining values back together with the same delimiters. Each field must be joined with a comma to form one line, and each line must end with "\n" so the next record starts on a new line when the file is read back later. Critically, only strings can be joined with + — any field that is currently an integer (such as price or stock on an Item record) must be explicitly converted with str() (the reverse of SDD10/SDD11's int()) before it can be concatenated into the line. Skipping this step does not silently produce a wrong answer the way a missing int() did in SDD11 — attempting to concatenate a string directly with an integer using + raises a TypeError immediately.

"w" — write mode
Opening an existing file in "w" mode erases its current contents first.
file = open("tuckshop.csv", "w")
file.write("Chocolate,75,30\n")
file.close()
Anything previously stored in tuckshop.csv is gone the moment this open() line runs — the file now contains only the one new line just written.
"a" — append mode
Opening the same file in "a" mode instead adds to the end, keeping everything already there.
file = open("tuckshop.csv", "a")
file.write("Muffin,120,18\n")
file.close()
Every line that was already in tuckshop.csv is preserved; only the new Muffin line is added after them.
1
Open the file in the correct mode
file = open("tuckshop.csv", "a") — choose "w" to replace the file, or "a" to add to it.
2
Convert non-string fields
str(item.price), str(item.stock) — every non-string field must be cast before it can be joined with +.
3
Build the CSV line
line = item.name + "," + str(item.price) + "," + str(item.stock) + "\n" — commas between fields, "\n" at the end.
4
Write the line
file.write(line) — writes exactly the string given, with no automatic newline.
5
Close the file
file.close() — always close a file once writing is finished.

Worked examples

Example 1 — Writing a single line of plain text
1
file = open("notice.txt", "w")
file.write("Tuck shop closes early on Fridays")
file.close()
2
"w" mode opens (and, if needed, creates) notice.txt; .write() sends the given text into it; .close() releases the file.
notice.txt now contains exactly Tuck shop closes early on Fridays — nothing more, since .write() added no extra characters.
Example 2 — Forgetting newline characters between writes
1
file = open("test.txt", "w")
file.write("line one")
file.write("line two")
file.close()
2
Neither .write() call includes a newline character, so Python does not insert one automatically between them.
test.txt contains line oneline two as a single unbroken line — verified by an actual Python run. Adding "\n" to the end of each .write() call ("line one\n", "line two\n") produces the two separate lines that were intended.
Example 3 — TypeError from an unconverted field
1
Using the tuck shop Item @dataclass from SDD6–11:
newItem = Item("Muffin", 120, 18)
line = newItem.name + "," + newItem.price + "," + newItem.stock
2
newItem.name is a string, but newItem.price and newItem.stock are integers. The + operator cannot join a string directly to an integer.
This raises TypeError: can only concatenate str (not "int") to str — confirmed by an actual Python run. The fix is to wrap each numeric field in str(): newItem.name + "," + str(newItem.price) + "," + str(newItem.stock).
Example 4 — Writing a whole array of records to CSV
1
Given the five-item itemRecords list from SDD11, plus one new item to add:
newItem = Item("Muffin", 120, 18)
itemRecords.append(newItem)

file = open("tuckshop.csv", "w")
for item in itemRecords:
    line = item.name + "," + str(item.price) + "," + str(item.stock) + "\n"
    file.write(line)
file.close()
2
"w" mode is used deliberately here, since the whole file is being regenerated from the full, up-to-date itemRecords list — including the newly appended Muffin — not just added to.
Confirmed by an actual Python run: tuckshop.csv now contains six lines, each correctly comma-separated and newline-terminated, ending with Muffin,120,18.
Now you try
Write the Python code needed to open "log.txt" in append mode, write the single line "Stock updated" followed by a newline, and close the file.
⚠️ Common mistakes — examiner feedback
📝 Exam tip

When a question asks about writing to an existing file, always state explicitly whether "w" or "a" mode is appropriate and justify the choice — "opens the file for writing" alone will not distinguish between overwriting and appending, and examiners specifically test this distinction. When tracing code that builds a CSV line, check every field's data type before assuming the concatenation will work — a missing str() is one of the most common single-line bugs in this part of the course.

Task Set A — Core questions

Task Set A — Core questions
Work through all questions, then check your answers.
Question 1
Which mode, passed as open()'s second argument, opens a file for writing and erases its existing contents?
Question 2
Which mode, passed as open()'s second argument, adds new data to the end of a file without erasing what is already there?
Question 3
A file already contains 3 lines. It is opened with open("data.txt", "w") and one new line is written. How many lines does the file contain afterwards?
Question 4
A program calls file.write("A") then file.write("B") with no newline characters in either string. What single string does the file now contain?
Question 5
stock holds the integer 18. What is the result of "Stock: " + stock?
Question 6
Which pre-defined function converts an integer to a string so it can be concatenated with +?
Question 7
Explain the difference between "w" and "a" mode, and give one situation where each would be the more appropriate choice. (4 marks)
Question 8
Write Python code that opens "tuckshop.csv" in write mode and writes one line for every Item record in itemRecords, each formatted as name,price,stock followed by a newline, then closes the file.
file = open("tuckshop.csv", "w")
for item in itemRecords:
    line = item.name + "," + str(item.price) + "," + str(item.stock) + "\n"
    file.write(line)
file.close()
Question 9
A pupil writes line = newItem.name + "," + newItem.price, where newItem.price is an integer. Predict what happens when this line runs, and explain the fix. (3 marks)
Question 10
Explain how int() (used when reading, SDD11) and str() (used when writing, SDD12) relate to each other. (3 marks)

Task Set B — Extension

Task Set B — Extension · Beyond the specification
Longer written answers — no auto-check. Discuss your answers with your teacher.
Extension 1
Suggest one risk of using "w" mode to regenerate a whole CSV file from an in-memory list of records, if the program were to crash partway through writing.
Extension 2
Research Python's built-in csv module's writing functionality. Suggest one advantage it might have over building each CSV line manually with + and str(), as done in this lesson.
Extension 3
SDD13 onwards will cover standard algorithms (linear search, then finding a minimum/maximum). Suggest how file handling (SDD11/SDD12) and a standard algorithm might combine in a single program.
📁 File this in OneNote under:
Higher Computing Science → Software Design & Development → SDD12
📌 Teacher notes — not for pupils

Single period — narrower topic than SDD11, building directly on it. Completes the file-handling strand of the spec (SDD7–SDD12) in one continuous six-lesson run.

Suggested timing: 5 min warm-up + vocab · 15 min notes + mode-compare panel + file-flow pipeline (demonstrate the "w" vs "a" distinction live — it is the single highest-value thing to get across this lesson) · 15 min examples 1–4 · 5 min "now you try" · remainder Task Set A; Task Set B as homework/extension.

Key misconception: pupils often assume .write() behaves like print() and adds a newline automatically — it does not. Demonstrate Example 2's "line oneline two" result live, since a plausible-but-wrong assumption here is easy to miss when just reading code rather than running it.

This lesson directly fixes a real bug spotted in a colleague's ("Chris") equivalent teaching material (Lesson 8 file-handling-write PPTX, slide 6) during this session's research phase: that material concatenated a non-string dataclass field directly with + without str(), which was verified this session to raise a TypeError in actual Python execution. This lesson's Example 3 and Task Set A Q9 use that exact scenario deliberately, as a worked "what goes wrong" example rather than repeating the uncaught bug.

SQA command words covered: explain, describe, predict, write code.