bhylu.com

Advertisements

Python Write/Create Files

Writing a file needs a deliberate mode. The w mode replaces existing content, a appends, and x creates a new file but fails when it already exists.

Understand the idea

Use a context manager and an explicit encoding for text. The example only writes inside a temporary directory. Real application writes may also need an atomic replacement strategy, permissions, durable storage rules, and recovery from partial failure. Adding a newline is your responsibility when writing separate text records.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
    path = Path(folder) / "attendees.txt"
    path.write_text("Mira\n", encoding="utf-8")
    with path.open("a", encoding="utf-8") as stream:
        stream.write("Dev\n")
    print(path.read_text(encoding="utf-8"), end="")

Read the result

The final content contains Mira and Dev on separate lines.

Try one change

Use x to create a new file twice in a temporary directory and handle the second attempt's FileExistsError.