← Previous

Lesson 18

Write files

~40 min

1. Write Files in Python

Reading files allows your application to consume data, but writing files gives your program persistence. Whether you are generating downloadable PDF/CSV reports, saving game progress, writing system logs, or caching database queries, knowing how to create and modify files safely is an indispensable skill for Python developers.

Learning Objectives

  • Understand Python's write file modes: "w", "a", and "x".
  • Write single text strings using .write() and lists of lines using .writelines().
  • Format multi-line outputs correctly with line breaks (\n) and f-strings.
  • Prevent accidental data loss by selecting the correct opening mode.

2. Choosing the Right Opening Mode

Just like reading files, writing files starts with Python's built-in open() function wrapped inside a with statement context manager. However, the second parameter—the mode—determines how Python handles existing content:

  • "w" (Write): Creates a new file if it doesn't exist. WARNING: If the file already exists, Python completely erases (truncates) its previous contents!
  • "a" (Append): Creates a new file if it doesn't exist. If the file exists, new data is added to the very end without altering existing text.
  • "x" (Exclusive Creation): Creates a new file, but fails with an error (FileExistsError) if the file already exists—preventing accidental overwrites.

Python code example:

# 1. Opening in "w" mode (Overwrites existing content)
with open("notes.txt", "w") as file:
    file.write("This is a fresh start!")

# 2. Opening in "a" mode (Appends to the end)
with open("notes.txt", "a") as file:
    file.write("\nAdding a second line safely.")

3. File Modes Comparison

Choosing the wrong file mode is one of the most common causes of accidental data loss. Use this reference table to pick the exact right mode for your task:

Mode Creates New File? Overwrites Existing Data? Cursor Position Primary Use Case
"w" Yes YES (Erases all) Start of file Creating fresh reports, saving configuration files from scratch.
"a" Yes No (Appends) End of file System event logging, tracking user history over time.
"x" Yes Fails with error if file exists Start of file Safety-critical file creation where overwriting is forbidden.

4. Writing Data: .write() vs .writelines()

Python provides two primary methods for writing text streams to a file object:

1. The .write(string) Method

Writes a single string to the file. Note that .write() accepts only strings—passing integers, floats, or lists directly will cause a TypeError. Furthermore, unlike Python's print() function, .write() does not automatically add a newline character (\n).

Python code example:

with open("output.txt", "w") as file:
    file.write("Line 1\n")  # Explicit \n required for new lines!
    file.write("Line 2\n")
    
    # Writing numeric data requires string conversion str()
    score = 95
    file.write(f"Final Score: {score}\n")

2. The .writelines(iterable) Method

Writes a list (or any iterable) of strings to the file at once. Crucially, .writelines() does NOT insert newline characters between list elements automatically. You must ensure each string inside your list ends with \n.

Python code example:

items = ["Apple\n", "Banana\n", "Cherry\n"]

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

5. Creating Structured Data (CSV Example)

Combining f-strings with file writing allows you to export structured formats like Comma-Separated Values (CSV) that spreadsheet programs like Microsoft Excel or Google Sheets can open directly.

Python code example:

users = [
    {"name": "Alice", "role": "Admin", "score": 98},
    {"name": "Bob", "role": "Developer", "score": 85},
    {"name": "Charlie", "role": "Tester", "score": 91}
]

# Exporting data to a structured CSV file
with open("report.csv", "w") as file:
    # 1. Write Header Row
    file.write("Name,Role,Score\n")
    
    # 2. Write Data Rows using f-strings
    for user in users:
        file.write(f"{user['name']},{user['role']},{user['score']}\n")

print("Report exported successfully!")

6. Real World Example: Automated Application Logger

In production applications, server events and errors are continuously recorded to an append-only log file so engineers can diagnose issues later without resetting system history.

from datetime import datetime

def log_event(event_message, level="INFO"):
    """Appends a timestamped log entry to app.log."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{timestamp}] [{level}] {event_message}\n"
    
    # Mode "a" ensures existing logs are preserved
    with open("app.log", "a") as log_file:
        log_file.write(log_entry)

# Simulating log entries
log_event("Application service started")
log_event("Database connection established")
log_event("Failed login attempt detected for user 'root'", level="WARNING")

# Reading back the log file to verify
with open("app.log", "r") as log_file:
    print(log_file.read())

7. Common Beginner Mistakes

⚠️ Watch out for these mistakes:

  • Accidental Overwriting with Mode "w": Using "w" when you meant to append ("a") instantly deletes all previous content in the target file without warning!
  • Forgetting Newline Characters (\n): Writing multiple lines with .write("Line 1") and .write("Line 2") results in Line 1Line 2 on a single long line.
  • Passing Non-String Types to .write(): Calling file.write(100) or file.write(my_list) raises a TypeError: write() argument must be str, not int. Convert non-strings using str() or f-strings.
  • Assuming .writelines() Adds Newlines: .writelines(["A", "B", "C"]) writes ABC as a single line unless you explicitly add \n to each string item.

8. Code Examples

Here are essential patterns for safely creating and writing files in Python:

# 1. Safe File Creation using Exclusive Mode ("x")
try:
    with open("config.json", "x") as file:
        file.write('{"theme": "dark", "version": "1.0"}')
    print("Configuration file created!")
except FileExistsError:
    print("Warning: 'config.json' already exists! Operation skipped to prevent overwrite.")

# 2. Writing clean list data with a single join operation
tags = ["python", "coding", "webdev", "tutorial"]

with open("tags.txt", "w") as file:
    # Pythonic shortcut: join items with newlines!
    file.write("\n".join(tags) + "\n")
Interactive Practice

Mini Practice: Daily Journal Entry

Write a script using a with statement that opens a file named "journal.txt" in append mode ("a"). Write a new entry string ending with \n, then print a confirmation message.

0% complete
Check when done
Quiz

Test Your Understanding

1. What happens when you open an existing text file in mode "w"?

2. Which opening mode should you use to create a file safely ONLY if it does not already exist?

3. What error occurs if you pass an integer directly into `file.write(42)`?

4. Does the `.writelines()` method automatically add line breaks (\n) between items in a list?

9. Challenge Project

Interactive Note Manager: Create a Python program that prompts the user to type a note from the command line. Ask if they want to 1. Overwrite or 2. Append. Based on their choice, open "my_notes.txt" in mode "w" or "a", save their input with a timestamp, and display the full updated contents of the file!

10. Key Takeaways

  • Use "w" to overwrite files, "a" to append data, and "x" to prevent accidental overwrites.
  • Always manage file handles using the with statement to ensure safe closing.
  • The .write() method takes only string arguments and does not add line breaks automatically.
  • Use explicit \n newline characters or f-strings to format multi-line files and CSV exports.
  • Remember that .writelines() requires pre-formatted string elements containing their own \n characters.

🚀 Progression

You've mastered Reading and Writing files in Python! Next up, we will dive into handling unexpected crashes with **Exception Handling in Python**!