- Write text to files using different modes
- Understand the difference between write and append
- Use write() and writelines() methods
- Handle file writing safely and efficiently
Writing Files
Reading files is like listening. Writing files is like speaking – your program has something to say, and files are where it says it permanently. Whether you're saving game progress, logging events, exporting data, or creating reports, writing files is how your programs leave a lasting mark.
In this lesson, you'll learn how to write files safely, understand the crucial difference between write and append modes, and discover best practices for file creation.
Writing Modes
Choosing the right mode is critical – one wrong choice and you could accidentally erase all your data!
Writing Modes Comparison
MODE 'w' - WRITE (Overwrite)
Before: → After:
Old content New content
Still here
WARNING: Old content is DELETED!
MODE 'a' - APPEND (Add to end)
Before: → After:
Old content Old content
New content
SAFE: Old content is PRESERVED!
Basic Writing
Write Mode ('w') - Start Fresh
# Creates new file or OVERWRITES existing!
with open("greeting.txt", "w") as file:
file.write("Hello, World!")
# Check the content
with open("greeting.txt", "r") as file:
print(file.read()) # Hello, World!
Append Mode ('a') - Add to Existing
# Adds to end of file (creates if doesn't exist)
with open("log.txt", "a") as file:
file.write("User logged in\n")
# Call again - adds another line
with open("log.txt", "a") as file:
file.write("User performed action\n")
# File now contains both lines!
Real-World Analogy
Real-World Analogy
MODE 'w' = Using a whiteboard
• Erase everything first
• Then write new content
• Previous notes are GONE
MODE 'a' = Using a notebook
• Turn to the next blank page
• Write new content
• Previous notes are SAFE
Writing Methods
write() - Write a String
with open("output.txt", "w") as file:
file.write("Line 1") # No automatic newline!
file.write("Line 2") # Continues on same line
file.write("\n") # NOW we add a newline
file.write("Line 3\n") # Include newline in string
Result in file:
Line 1Line 2
Line 3
writelines() - Write Multiple Strings
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as file:
file.writelines(lines) # Writes all at once
Important: writelines() does NOT add newlines automatically!
# WRONG - no newlines between items
lines = ["Apple", "Banana", "Cherry"]
with open("fruits.txt", "w") as file:
file.writelines(lines)
# File content: AppleBananaCherry
# CORRECT - include newlines
lines = ["Apple\n", "Banana\n", "Cherry\n"]
with open("fruits.txt", "w") as file:
file.writelines(lines)
# File content:
# Apple
# Banana
# Cherry
The print() Shortcut
You can use print() to write to files too!
with open("output.txt", "w") as file:
print("Hello!", file=file) # Adds newline automatically
print("How are you?", file=file) # Another line
print(42, file=file) # Converts to string automatically
print() vs write()
| Feature | write() | print(file=f) |
|---|---|---|
| Adds newline | No | Yes |
| Converts types | No (strings only) | Yes |
| Multiple args | No | Yes |
| Separator option | No | Yes (sep=) |
# print() is often more convenient
with open("data.txt", "w") as file:
print("Name:", "Alice", file=file) # Name: Alice
print(1, 2, 3, sep="-", file=file) # 1-2-3
print("No newline", end="", file=file) # Custom line ending
Practical Examples
Example 1: Saving User Data
def save_user(filename, name, email, age):
"""Save user information to a file."""
with open(filename, "w", encoding="utf-8") as file:
file.write(f"Name: {name}\n")
file.write(f"Email: {email}\n")
file.write(f"Age: {age}\n")
print(f"User saved to {filename}")
save_user("user.txt", "Alice", "alice@example.com", 25)
Example 2: Simple Logger
from datetime import datetime
def log_message(filename, message):
"""Append a timestamped message to a log file."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(filename, "a", encoding="utf-8") as file:
file.write(f"[{timestamp}] {message}\n")
# Usage
log_message("app.log", "Application started")
log_message("app.log", "User logged in")
log_message("app.log", "Data processed successfully")
# Each call ADDS to the file, never erases!
Example 3: Export to CSV
def export_to_csv(filename, headers, data):
"""Export data to a CSV file."""
with open(filename, "w", encoding="utf-8") as file:
# Write header row
file.write(",".join(headers) + "\n")
# Write data rows
for row in data:
file.write(",".join(str(item) for item in row) + "\n")
print(f"Exported {len(data)} rows to {filename}")
# Usage
headers = ["Name", "Age", "City"]
data = [
["Alice", 25, "Paris"],
["Bob", 30, "London"],
["Charlie", 35, "New York"]
]
export_to_csv("users.csv", headers, data)
Example 4: Configuration Writer
def save_config(filename, config):
"""Save configuration dictionary to a file."""
with open(filename, "w", encoding="utf-8") as file:
file.write("# Configuration File\n")
file.write(f"# Generated: {datetime.now()}\n\n")
for key, value in config.items():
file.write(f"{key}={value}\n")
config = {
"theme": "dark",
"language": "en",
"notifications": "true",
"font_size": 14
}
save_config("settings.cfg", config)
Common Mistakes
1. Accidentally Overwriting
# DANGER: This erases important_data.txt!
with open("important_data.txt", "w") as file:
file.write("New data")
# SAFE: Check if file exists first
import os
if os.path.exists("important_data.txt"):
print("File exists! Use 'a' to append or choose different name")
else:
with open("important_data.txt", "w") as file:
file.write("New data")
2. Forgetting Newlines
# BAD: All on one line
with open("list.txt", "w") as file:
file.write("Apple")
file.write("Banana")
file.write("Cherry")
# File: AppleBananaCherry
# GOOD: Add newlines
with open("list.txt", "w") as file:
file.write("Apple\n")
file.write("Banana\n")
file.write("Cherry\n")
3. Not Specifying Encoding
# May fail with special characters
with open("french.txt", "w") as file:
file.write("Café résumé") # Might cause issues!
# Always specify UTF-8
with open("french.txt", "w", encoding="utf-8") as file:
file.write("Café résumé") # Works perfectly!
Key Takeaways
Remember These Points
Mode 'w' = Overwrite (erases existing content)
Mode 'a' = Append (keeps existing content)
write() does NOT add newlines
You must include '\n' yourself
print(file=f) is often more convenient
Auto-converts types and adds newlines
Always use encoding="utf-8"
Be careful with 'w' - it deletes content!
Consider checking if file exists first
What's Next?
You can now read and write files! But how do you navigate to find them? In the next lesson, we'll explore working with paths – how to locate files, build paths correctly, and navigate the file system.
