Unit 11.4A · Term 4

Writing Files

Writing files allows your program to save data permanently — results, reports, logs, and user data that persist after the program ends. Master both write mode (overwrite) and append mode (add to end).

Learning Objectives

  • 11.4.1.2 Write data to text files

Lesson Presentation

11.4A-lesson-22-file-write.pdf · Slides for classroom use

Conceptual Anchor

Writing vs Appending

Write mode ("w") is like getting a fresh notebook — it erases everything and starts from scratch. Append mode ("a") is like opening your notebook to the last page and continuing where you left off. Choose wisely!

Rules & Theory

Writing to Files

# Write mode — creates new file or OVERWRITES existing! with open("output.txt", "w") as file: file.write("Hello, World!\n") file.write("This is line 2.\n") file.write(f"Score: {95}\n") # Append mode — adds to end of existing file with open("log.txt", "a") as file: file.write("New entry added\n") # writelines() — write a list of strings lines = ["Line 1\n", "Line 2\n", "Line 3\n"] with open("output.txt", "w") as file: file.writelines(lines)

Write vs Append

Feature Write ("w") Append ("a")
Existing file Overwrites (deletes old content!) Adds to end
New file Creates it Creates it
Use for Fresh output, reports Logs, adding records
Danger Data loss if not careful! File grows over time

Writing Different Data Types

# write() only accepts strings! score = 95 name = "Ali" with open("result.txt", "w") as file: # Must convert to string file.write(str(score) + "\n") # Explicit conversion file.write(f"{name},{score}\n") # f-string (cleaner!) # Writing from a list scores = [85, 90, 78, 92] for s in scores: file.write(f"{s}\n") # Using print() with file parameter print("This goes to file!", file=file) print(score, file=file)

Remember: Newlines Are Manual

Unlike print(), file.write() does NOT add a newline automatically. You must include \n yourself at the end of each line.

Worked Examples

1 Saving Student Data as CSV

students = [ ("Ali", 16, 95), ("Dana", 15, 88), ("Marat", 16, 72) ] with open("students.csv", "w") as file: file.write("Name,Age,Score\n") # Header row for name, age, score in students: file.write(f"{name},{age},{score}\n") print("Data saved to students.csv!")

2 Read → Process → Write

# Read scores, calculate grade, write results with open("scores.txt", "r") as infile: scores = [int(line.strip()) for line in infile] def get_grade(s): if s >= 90: return "A" if s >= 80: return "B" if s >= 70: return "C" if s >= 60: return "D" return "F" with open("results.txt", "w") as outfile: outfile.write("Score,Grade\n") for score in scores: grade = get_grade(score) outfile.write(f"{score},{grade}\n") outfile.write(f"\nAverage: {sum(scores)/len(scores):.1f}\n")

3 Activity Logger

from datetime import datetime def log_activity(activity): """Append a timestamped entry to the log file.""" timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open("activity_log.txt", "a") as file: file.write(f"[{timestamp}] {activity}\n") # Each call ADDS to the file (doesn't overwrite) log_activity("User logged in") log_activity("Viewed dashboard") log_activity("Updated profile")

Pitfalls & Common Errors

"w" Mode Destroys Data!

Opening a file in "w" mode immediately erases all content, even if you don't write anything. Always double-check before using write mode on important files.

write() Doesn't Add Newlines

file.write("Hello") followed by file.write("World") produces HelloWorld — all on one line. Include \n yourself.

write() Only Accepts Strings

file.write(42) raises TypeError. Convert first: file.write(str(42)) or use f"{42}".

Pro-Tips for Exams

File Writing Tips

  • print(data, file=outfile) — automatically adds \n, easier than write()
  • CSV pattern: file.write(",".join([str(x) for x in row]) + "\n")
  • Always use "a" for logs and records that should accumulate
  • Use "w" only for creating fresh output files

Graded Tasks

Remember

What is the difference between "w" and "a" mode?

Understand

Why does file.write(42) cause an error? What is the fix?

Apply

Write a program that asks for 5 names and saves them to a file, one per line.

Apply

Read numbers from input.txt, double each one, and write results to output.txt.

Analyze

What happens if you open a file with "w", write nothing, and close it? What about with "a"?

Create

Build a diary program: users enter text entries that are appended to a file with timestamps. Include a "read all entries" option.

Self-Check Quiz

1. What mode opens a file for writing (overwriting)?
Click to reveal answer
2. Does file.write() add a newline automatically?
Click to reveal answer
3. How do you add data to an existing file without erasing it?
Click to reveal answer
4. Can write() accept an integer?
Click to reveal answer
5. How do you write a list to a file, one item per line?
Click to reveal answer