
Python
Learn different ways to write data to files and manage file creation/overwriting.
Use `write()` to save data to a file.
# Open file for writing (creates if doesn't exist, overwrites if it does)
file = open("output.txt", "w")
# Write some text
file.write("Hello, World!\n")
file.write("This is line 2\n")
# IMPORTANT: Must close to save
file.close()
# File now contains:
# Hello, World!
# This is line 2Choose the right mode: `"w"` (overwrite) or `"a"` (append).
# Write mode - overwrites existing file
file = open("log.txt", "w")
file.write("New message\n")
file.close()
# Old content is GONE
# Append mode - adds to end
file = open("log.txt", "a")
file.write("Another message\n")
file.close()
# Old content preserved, new message added# Append timestamped log entries
from datetime import datetime
log_file = open("app.log", "a")
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_file.write(f"[{timestamp}] Application started\n")
log_file.write(f"[{timestamp}] User logged in\n")
log_file.close()| Method | Effect | Use Case |
|---|---|---|
| `write(text)` | Write once | Single writes |
| `writelines(list)` | Write multiple strings | Batch writes |
| Mode `"w"` | Overwrite file | Start fresh |
| Mode `"a"` | Append to end | Add to existing |
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward