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()andwritelines(). - Safety Warning: How to avoid accidentally deleting your data!
1. Write Mode ('w')
When you open a file with 'w', Python does two things:
- If the file doesn't exist, it creates it.
- 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
| Mode | What it does | If file exists... | If file doesn't exist... |
|---|---|---|---|
'r' | Read only | Opens it | Error! |
'w' | Write only | Erases it | Creates it |
'a' | Append only | Adds to the end | Creates it |
Practice Exercise: The Diary App
Create a file named diary.py.
- Ask the user:
"What's on your mind today?" - Open a file named
my_diary.txtin append mode. - Write the user's input to the file.
- Add a timestamp (remember the
datetimemodule from Module 3?) to each entry. - Close the program and run it a few times. Check
my_diary.txtto see all your entries saved!
Quick Knowledge Check
- What is the main danger of using
"w"mode? - What mode should you use if you want to create a log file that keeps all previous messages?
- Do you need to add
\nyourself when usingwrite(), or does Python do it for you? - 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!