SDD12 — File Handling: Writing
- I can open a file for writing or appending, write data to it, and close it
- I can explain the difference between write mode and append mode
- I can convert data back into correctly formatted CSV text before writing it to a file
- I can use
open()with"w"or"a"mode,.write(), and.close()to save data to a file - I can explain that
"w"mode overwrites a file's existing contents, while"a"mode adds to the end without erasing anything - I can build a correctly formatted CSV line by joining fields with commas and adding a newline character, converting non-string fields with
str()first
open()'s second argument, opens a file for reading?split(","). What data type is every individual field in the result, before any further conversion?split() to be called twice?Key vocabulary
.write()str() converting an integer to a string.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" 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" 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.
file = open("tuckshop.csv", "a") — choose "w" to replace the file, or "a" to add to it.str(item.price), str(item.stock) — every non-string field must be cast before it can be joined with +.line = item.name + "," + str(item.price) + "," + str(item.stock) + "\n" — commas between fields, "\n" at the end.file.write(line) — writes exactly the string given, with no automatic newline.file.close() — always close a file once writing is finished.Worked examples
file = open("notice.txt", "w")
file.write("Tuck shop closes early on Fridays")
file.close()"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.file = open("test.txt", "w")
file.write("line one")
file.write("line two")
file.close().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.Item @dataclass from SDD6–11:
newItem = Item("Muffin", 120, 18)
line = newItem.name + "," + newItem.price + "," + newItem.stocknewItem.name is a string, but newItem.price and newItem.stock are integers. The + operator cannot join a string directly to an integer.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).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()"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.tuckshop.csv now contains six lines, each correctly comma-separated and newline-terminated, ending with Muffin,120,18."log.txt" in append mode, write the single line "Stock updated" followed by a newline, and close the file.
- Using
"w"when"a"was intended. Opening an existing file in"w"mode erases its entire current content immediately — a serious, silent data-loss bug, not just a wrong-answer bug. - Forgetting
"\n"between writes..write()never adds a newline automatically; without one, separate.write()calls run together onto a single line. - Forgetting to convert non-string fields with
str(). Concatenating a string and an integer directly with+raises aTypeErrorimmediately — unlike SDD11's missing-int()mistake, this one does not run silently. - Confusing
.write()withprint().print()sends text to the screen and adds a newline automatically;.write()sends text to a file and does not. - Forgetting to close the file. Data written to a file is not always guaranteed to be fully saved until
.close()is called.
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
open()'s second argument, opens a file for writing and erases its existing contents?open()'s second argument, adds new data to the end of a file without erasing what is already there?open("data.txt", "w") and one new line is written. How many lines does the file contain afterwards?file.write("A") then file.write("B") with no newline characters in either string. What single string does the file now contain?stock holds the integer 18. What is the result of "Stock: " + stock?+?"w" and "a" mode, and give one situation where each would be the more appropriate choice. (4 marks)"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()
line = newItem.name + "," + newItem.price, where newItem.price is an integer. Predict what happens when this line runs, and explain the fix. (3 marks)int() (used when reading, SDD11) and str() (used when writing, SDD12) relate to each other. (3 marks)Task Set B — Extension
"w" mode to regenerate a whole CSV file from an in-memory list of records, if the program were to crash partway through writing.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.Higher Computing Science → Software Design & Development → SDD12
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.