Skip to content

Writing to Text FilesActivities & Teaching Strategies

Active learning engages students with immediate feedback loops when writing to files, turning abstract persistence concepts into tangible results they can inspect and discuss. Hands-on file creation and inspection build muscle memory for open(), write(), and close() sequences that textbooks often leave as dry theory.

Year 9Computing4 activities20 min45 min

Learning Objectives

  1. 1Design a Python program that accepts user input and writes it to a specified text file.
  2. 2Compare the outcomes of using 'w' (write) mode versus 'a' (append) mode when writing to text files.
  3. 3Explain the necessity of data persistence for applications requiring long-term data storage, such as game high scores.
  4. 4Evaluate the potential errors, like file permission issues, that can occur when writing to files and suggest basic handling strategies.

Want a complete lesson plan with these objectives? Generate a Mission

30 min·Pairs

Pair Challenge: High-Score Tracker

Pairs write a program that asks for a name and score, then appends it to 'highscores.txt'. Test by running multiple times and viewing the file. Discuss why 'a' mode prevents data loss.

Prepare & details

Justify the need for data persistence in applications like a high-score tracker.

Facilitation Tip: During the Pair Challenge, circulate with a file explorer open on your device to show students where to look for their saved files after each write.

Setup: Flexible workspace with access to materials and technology

Materials: Project brief with driving question, Planning template and timeline, Rubric with milestones, Presentation materials

ApplyAnalyzeEvaluateCreateSelf-ManagementRelationship SkillsDecision-Making
45 min·Small Groups

Small Group: Note-Taking App

Groups design a loop for user notes input, save to 'notes.txt' using 'w' first then 'a' for additions. Run, edit file externally, rerun to observe overwrites. Compare file states.

Prepare & details

Design a program that allows a user to input notes and saves them to a text file.

Facilitation Tip: For the Small Group Note-Taking App, require groups to swap laptops midway to inspect each other’s file contents and modes used.

Setup: Flexible workspace with access to materials and technology

Materials: Project brief with driving question, Planning template and timeline, Rubric with milestones, Presentation materials

ApplyAnalyzeEvaluateCreateSelf-ManagementRelationship SkillsDecision-Making
25 min·Individual

Individual Debug: Write vs Append

Each student codes two functions: one overwrites 'test.txt' with new data, one appends. Input varied data, inspect files after each run. Log observations in a table.

Prepare & details

Compare the implications of 'writing' versus 'appending' data to a file.

Facilitation Tip: In the Individual Debug activity, provide a printout of the error messages so students can annotate corrections before editing their code.

Setup: Flexible workspace with access to materials and technology

Materials: Project brief with driving question, Planning template and timeline, Rubric with milestones, Presentation materials

ApplyAnalyzeEvaluateCreateSelf-ManagementRelationship SkillsDecision-Making
20 min·Whole Class

Whole Class: File Review Relay

Project one shared file; class suggests inputs via mini whiteboards. Teacher runs code live, class predicts file changes. Vote on 'w' or 'a' for scenarios.

Prepare & details

Justify the need for data persistence in applications like a high-score tracker.

Setup: Flexible workspace with access to materials and technology

Materials: Project brief with driving question, Planning template and timeline, Rubric with milestones, Presentation materials

ApplyAnalyzeEvaluateCreateSelf-ManagementRelationship SkillsDecision-Making

Teaching This Topic

Teachers should model the complete workflow: open, write, close, verify. Avoid demonstrations that skip the file explorer step—students need to see the physical artifact to believe persistence. Emphasize that 'w' mode is destructive; use metaphors like 'overwriting a journal page' to make the risk concrete.

What to Expect

Students will confidently choose between 'w' and 'a' modes, convert data to strings, and verify file contents after each activity. Successful work includes correctly saved data, proper file closing, and clear explanations of when to overwrite versus append.

These activities are a starting point. A full mission is the experience.

  • Complete facilitation script with teacher dialogue
  • Printable student materials, ready for class
  • Differentiation strategies for every learner
Generate a Mission

Watch Out for These Misconceptions

Common MisconceptionDuring the Pair Challenge, watch for students who assume the file updates automatically without calling write() or close().

What to Teach Instead

Ask pairs to open the file in a text editor after each input step to confirm no changes appear until write() is called, reinforcing the need for explicit write and close calls.

Common MisconceptionDuring the Small Group Note-Taking App, watch for students who believe 'w' mode appends content to existing files.

What to Teach Instead

Have groups save identical files using both 'w' and 'a' modes side-by-side, then open both in a text editor to observe that only the 'a' file preserves old content.

Common MisconceptionDuring the Individual Debug Write vs Append activity, watch for students who try to write non-string data directly to files.

What to Teach Instead

Ask students to run their code and observe the TypeError, then guide them to insert str() conversions before write(), modeling the error-handling process.

Assessment Ideas

Exit Ticket

After the Pair Challenge, ask students to write a brief explanation on an exit ticket: 'Why did we use append mode in our high-score tracker? What would happen if we used write mode instead?' Collect and review for accurate reasoning about data persistence.

Quick Check

During the Small Group Note-Taking App, circulate and observe each group’s code snippet for correct use of open('notes.txt', 'a'), writelines(), and explicit close(). Note any groups missing these elements for targeted feedback.

Discussion Prompt

After the Whole Class File Review Relay, pose the discussion prompt: 'Imagine you have a file with student names and their test scores. If you want to add a new student's score without deleting the existing ones, what Python command should you use? What if you wanted to update a student's score with a new one, replacing the old score?' Use responses to assess understanding of 'a' versus 'w' mode implications.

Extensions & Scaffolding

  • Challenge: Ask students to create a leaderboard that sorts scores and writes the top five to a file in descending order.
  • Scaffolding: Provide a starter code snippet with comments for each step (open, convert score to string, write, close) and space for students to fill in their own filenames and content.
  • Deeper exploration: Introduce os.path.exists() and conditional logic to check before overwriting a file, prompting users to confirm the action.

Key Vocabulary

File HandleAn object representing the connection between a Python program and a file on the computer. It is used to perform operations like reading or writing.
Write Mode ('w')Opens a file for writing. If the file exists, its contents are deleted. If the file does not exist, it is created.
Append Mode ('a')Opens a file for appending. New data is added to the end of the file. If the file does not exist, it is created.
Data PersistenceThe ability of data to exist beyond the duration of a single program execution, typically by being stored in files or databases.

Ready to teach Writing to Text Files?

Generate a full mission with everything you need

Generate a Mission