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")
β
 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")
β
 "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)
  
  
  π§  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!")
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))
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!")
π οΈ 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")
π 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
- Create a program that writes user input to a file until they type "exit".
- Build a simple logger that writes timestamps and messages to a file.
- Write a list of names to a file, one per line, and then append more names later.
 
 
              
 
    
Top comments (0)