DEV Community

Cover image for Day 42/100: Writing Files and Using Context Managers in Python
 Rahul Gupta
Rahul Gupta

Posted on

Day 42/100: Writing Files and Using Context Managers in Python

Welcome to Day 42 of your Python journey!
Yesterday, we explored reading files using open(). Today, we’ll move on to writing and appending files, while also mastering context managers to handle files safely.


πŸ“₯ 1. Writing Files with open()

To create or overwrite a file, use the "w" mode:

# Creates a new file or overwrites existing one
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("This will overwrite the file content.\n")
Enter fullscreen mode Exit fullscreen mode

βœ… Note: "w" erases all existing content before writing.


πŸ“„ 2. Appending to Files

To add content without deleting existing data, use "a" mode:

with open("output.txt", "a") as f:
    f.write("Appending a new line.\n")
Enter fullscreen mode Exit fullscreen mode

βœ… "a" keeps the old data and adds new content at the end.


πŸ” 3. Writing Multiple Lines

You can write a list of strings with writelines():

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)
Enter fullscreen mode Exit fullscreen mode

🧠 4. Using Context Managers (with)

You might notice we’re using with open(...) as f: everywhere. This is a context manager.

Why use with?

  • Automatically closes the file.
  • Prevents resource leaks.
  • Handles errors gracefully.
with open("example.txt", "w") as f:
    f.write("Safe and clean file handling!")
Enter fullscreen mode Exit fullscreen mode

No need to call f.close() β€” Python handles it for you.


πŸ“Œ 5. Writing Different Data Types

You can only write strings to files. For other types, convert them:

data = {"name": "Alice", "age": 30}

with open("data.txt", "w") as f:
    f.write(str(data))
Enter fullscreen mode Exit fullscreen mode

For structured data, consider using JSON (Day 36 covered this).


πŸ”„ 6. Handling Errors Safely

Always handle exceptions when dealing with file writing:

try:
    with open("output.txt", "w") as f:
        f.write("Important data")
except IOError:
    print("Error writing to file!")
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ Real-World Example: Logging System

from datetime import datetime

def log_event(message):
    with open("log.txt", "a") as f:
        f.write(f"[{datetime.now()}] {message}\n")

log_event("User logged in")
log_event("User uploaded a file")
Enter fullscreen mode Exit fullscreen mode

πŸ“œ Summary

  • "w" = Write (creates/overwrites file)
  • "a" = Append (adds to existing file)
  • Always use with open() to manage resources automatically.
  • Convert non-string data before writing.
  • Use error handling to avoid crashes during file operations.

πŸ§ͺ Practice Challenge

  1. Create a program that writes user input to a file until they type "exit".
  2. Build a simple logger that writes timestamps and messages to a file.
  3. Write a list of names to a file, one per line, and then append more names later.

Top comments (0)