</>
Skip to content
Python lessons (40/45)

Python — Write Files

Writing text

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("First line\n")
    f.write("Second line\n")

write() does NOT add newlines — you supply every \n.

"w" destroys instantly: opening with w erases the existing file before you write a character. Accidental data loss lives here.

Append — the non-destructive default choice

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("2026-08-23 user logged in\n")

Create-only: "x"

try:
    with open("config.json", "x") as f:    # fails if file exists
        f.write("{}")
except FileExistsError:
    print("already exists — refusing to overwrite")

writelines & building content

lines = [f"{name}: {score}\n" for name, score in scores.items()]

with open("scores.txt", "w") as f:
    f.writelines(lines)        # no newlines added — include them yourself

Structured output via modules

import json

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

import csv
with open("report.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "score"])
    writer.writerows(scores.items())

A small logging helper

def log(msg):
    from datetime import datetime
    stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open("app.log", "a", encoding="utf-8") as f:
        f.write(f"[{stamp}] {msg}\n")

log("started")
log("error on step 3")

Open-append-close per entry = other programs can read the file live.

Safe replacement pattern

Overwriting important files? Write-then-rename is crash-safe:

import os, tempfile

tmp = tempfile.NamedTemporaryFile("w", delete=False, dir=".")
tmp.write(new_contents)
tmp.close()
os.replace(tmp.name, "important.json")   # atomic on same filesystem

Worst case you keep old OR new file, never half of each.

Gotchas: forgetting \n (one giant line) · writing without encoding on Windows · two processes appending simultaneously can interleave lines · "w" + crash = lost file.

Mini Practice

  1. Write a 3-line poem; verify by reading back.
  2. Log-helper with timestamps; call it five times.
  3. Export dict → JSON file; CSV table via csv module.
  4. Prove "w" vs "a" difference on the same file.
  5. Use "x" to guard against overwriting an existing config.

Next: delete files →

Related Topics

Frequently Asked Questions about Write Files

What is Write Files in Python?

Write Files is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Write Files?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Write Files.

Why is Write Files important in Python?

Write Files is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.