Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
📖 File Fundamentals📖 Reading Files Effectively✍️ Writing Files Correctly🗂️ Working with File Paths🤝 Context Managers & Safety📊 CSV Data Processing🔄 JSON Parsing & Serialization🔐 Binary Files & Encoding⚙️ Performance & Best Practices
Python/File Io/Writing Files

✍️ Writing Files Correctly — Saving Data

Learn different ways to write data to files and manage file creation/overwriting.


🎯 Write to Files

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 2

💡 Append vs Write

Choose 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

🎨 Real-World Example: Writing Log Entries

# 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()

📊 Writing Techniques

MethodEffectUse Case
`write(text)`Write onceSingle writes
`writelines(list)`Write multiple stringsBatch writes
Mode `"w"`Overwrite fileStart fresh
Mode `"a"`Append to endAdd to existing

🔑 Key Takeaways

  • ✅ `write()` saves text to file
  • ✅ Mode `"w"` overwrites, `"a"` appends
  • ✅ Always close file to save data
  • ✅ `\n` needed for line breaks
  • ✅ Files created if they don't exist

Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn