Writing Text Files
Writing Text Files
Reading files is useful.
But many programs also need to save new data.
Examples:
- Save notes
- Store names
- Create reports
- Update logs
- Export results
Python can write text into files.
What Does Writing Mean?
Writing means sending text from your program into a file.
The file can be created or updated.
Opening a File for Writing
Use open() with mode "w".
file = open("notes.txt", "w")
"w" means write mode.
Important Warning
If the file already has content, "w" replaces the old content.
Writing Text
Use write().
file = open("notes.txt", "w")
file.write("Hello World")
file.close()
Now the file contains:
Hello World
Better Way: with open()
with open("notes.txt", "w") as file:
file.write("Hello World")
The file closes automatically.
Writing Multiple Lines
Use \n for a new line.
with open("notes.txt", "w") as file:
file.write("Learn Python\n")
file.write("Practice Daily\n")
File content:
Learn Python
Practice Daily
Append Mode
Use "a" to add new content without deleting old content.
with open("notes.txt", "a") as file:
file.write("Keep Going\n")
Updated file:
Learn Python
Practice Daily
Keep Going
Writing User Input
name = input("Enter your name: ")
with open("users.txt", "a") as file:
file.write(name + "\n")
This saves user names.
Common Beginner Errors
Using "w" by Mistake
This can erase old content.
Forgetting \n
Lines may join together.
Forgetting to Close
Use with open().
Code Along
Create a file named goals.txt.
Save:
Learn Python
Build Projects
Get Better
Mini Challenge
Build a journal saver.
Steps:
- Ask the user to enter one note
- Save the note into
journal.txt - Add a new line after the note
- Run again to keep adding notes
Hint: Use append mode.
Expected file example:
Today I learned files
Python is fun
Real World Use Case
Programs write reports, save notes, store usernames, create logs, and export data.
Quiz
- What does
"w"do? - What does
"a"do? - Why use
\n? - Why is
with open()useful?
Assignment
Create a program that asks for 3 tasks and saves them into tasks.txt, one per line.
Summary
You learned how to create files, write text, append new content, save user input, and safely handle file writing in Python.