Module 5 Lesson 2: Writing and Appending to Files
·Programming

Module 5 Lesson 2: Writing and Appending to Files

Save your data. Learn how to create new files, overwrite existing ones, and safely add new information to the end of a file.

Module 5 Lesson 2: Writing and Appending to Files

Reading data is useful, but saving data is what makes our applications powerful. Whether you're saving a user's high score, a grocery list, or a log of errors, you need to know how to Write and Append.

Lesson Overview

In this lesson, we will cover:

  • Write Mode ('w'): Creating and overwriting files.
  • Append Mode ('a'): Adding to the end of a file.
  • Writing Strings vs. Lists: write() and writelines().
  • Safety Warning: How to avoid accidentally deleting your data!

1. Write Mode ('w')

When you open a file with 'w', Python does two things:

  1. If the file doesn't exist, it creates it.
  2. If the file does exist, it ERASES EVERYTHING in it and starts fresh.
with open("my_story.txt", "w") as file:
    file.write("Once upon a time in a digital world...")

2. Append Mode ('a')

If you want to add data without deleting what's already there, use 'a' for append. This is like adding a new entry to a diary.

with open("my_story.txt", "a") as file:
    file.write("\nAnd then, the code started working!")

(Note: We added \n to ensure the new text starts on a new line!)


3. Writing Multiple Lines

If you have a list of strings, you can write them all at once using writelines().

shopping_list = ["Apples\n", "Milk\n", "Eggs\n"]

with open("groceries.txt", "w") as file:
    file.writelines(shopping_list)

4. Summary of File Modes

ModeWhat it doesIf file exists...If file doesn't exist...
'r'Read onlyOpens itError!
'w'Write onlyErases itCreates it
'a'Append onlyAdds to the endCreates it

Practice Exercise: The Diary App

Create a file named diary.py.

  1. Ask the user: "What's on your mind today?"
  2. Open a file named my_diary.txt in append mode.
  3. Write the user's input to the file.
  4. Add a timestamp (remember the datetime module from Module 3?) to each entry.
  5. Close the program and run it a few times. Check my_diary.txt to see all your entries saved!

Quick Knowledge Check

  1. What is the main danger of using "w" mode?
  2. What mode should you use if you want to create a log file that keeps all previous messages?
  3. Do you need to add \n yourself when using write(), or does Python do it for you?
  4. What happens if you try to write to a file opened in "r" mode?

Key Takeaways

  • 'w' overwrites; 'a' adds to the end.
  • file.write() expects a string.
  • file.writelines() expects a list of strings.
  • Always be careful with 'w' mode to avoid data loss.

What’s Next?

Plain text files are great, but businesses use CSV (Spreadsheets) and JSON to store data. In Lesson 3, we’ll learn how to handle CSV Data like a data scientist!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn