Course Progress47%
🍎 Python Basics Topic 47 / 100
⏳ 7 min read

Writing Files

Create files, save data, and append records — the difference between overwriting and appending is one letter.

"Reading gets data in. Writing sends data out. Together, files become your program's long-term memory."

— ShurAI

Writing to a File — "w" mode

Mode "w" creates the file if it doesn't exist. If it does exist, it wipes it completely and starts fresh — be careful!

python
with open("diary.txt", "w") as f:
    f.write("Day 1: Started learning Python.\n")
    f.write("Day 2: Learned about files.\n")
    f.write("Day 3: Built a project.\n")

print("File written.")

# Read it back to verify
with open("diary.txt", "r") as f:
    print(f.read())
"w" deletes first — always

Opening an existing file in "w" mode instantly empties it before you write a single character. To add to a file without destroying it, use "a" (append) instead.

Appending — "a" mode

Mode "a" adds to the end of an existing file. If the file doesn't exist, it creates it:

python
# First run — creates the file
with open("log.txt", "a") as f:
    f.write("User Riya logged in at 09:00\n")

# Second run — adds to the end, does NOT erase
with open("log.txt", "a") as f:
    f.write("User Arjun logged in at 09:15\n")

# log.txt now contains both lines
"w" — Write
⚠️ Overwrites existing file
📄 Creates file if it doesn’t exist
🗸 Starts from line 1 every time

Use for: generating reports, saving fresh data
"a" — Append
✔️ Adds to the end, never destroys
📄 Creates file if it doesn’t exist
🗸 Previous content stays safe

Use for: logs, diaries, collecting records

Writing Multiple Lines at Once

python
students = ["Riya", "Arjun", "Sneha", "Vikram"]

# writelines() — write a list of strings
with open("students.txt", "w") as f:
    f.writelines(name + "\n" for name in students)

# Alternative: join and write as one string
with open("students.txt", "w") as f:
    f.write("\n".join(students))

Real Example — Daily Activity Logger

python
from datetime import datetime

def log_activity(activity):
    """Append a timestamped entry to the activity log."""
    timestamp = datetime.now().strftime("%d/%m/%Y %H:%M")
    entry     = f"[{timestamp}] {activity}\n"
    with open("activity.log", "a") as f:
        f.write(entry)
    print(f"Logged: {activity}")

log_activity("Started Python lesson")
log_activity("Completed 3 quizzes")
log_activity("Finished reading files chapter")

# Show the log
with open("activity.log", "r") as f:
    print("\n--- Activity Log ---")
    print(f.read())
output
Logged: Started Python lesson
Logged: Completed 3 quizzes
Logged: Finished reading files chapter

--- Activity Log ---
[15/03/2026 14:20] Started Python lesson
[15/03/2026 14:21] Completed 3 quizzes
[15/03/2026 14:23] Finished reading files chapter

"The rule is simple: use ‘w’ when you want a fresh file every time, use ‘a’ when you want to keep adding. Get this wrong once and you’ll never forget it."

— ShurAI

🧠 Quiz — Q1

What happens when you open an existing file with mode "w"?

🧠 Quiz — Q2

You want to add new log entries to a file without deleting old ones. Which mode should you use?

🧠 Quiz — Q3

What does f.write("hello\n") do?

🧠 Quiz — Q4

What does f.writelines(["a\n","b\n"]) write?