Sub topic 2
Writing and Appending Text
Assume you know basic Python syntax, loops, functions, str versus bytes, and try/except. This chapter uses those skills to create text files reliably.
Writing and appending text
open() returns a file object. Its mode controls what happens to the file:
| Mode | Purpose |
|---|---|
| `"w"` | Write from the beginning; replace existing content |
| `"a"` | Append at the end; preserve existing content |
| `"x"` | Create a new file; fail if it already exists |
Use a with statement so Python closes the file even when an error occurs.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.writelines(["second line\n", "third line\n"])
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("appended line\n")write() accepts one string. writelines() accepts an iterable of strings, but it does not add newline characters automatically.
Encodings and newlines
An encoding maps characters to bytes. Use UTF-8 explicitly so the program behaves consistently across systems. Include \n when each record should end on a new line.
The newline argument matters most when writing structured text such as CSV. The csv module expects newline="", which prevents unwanted blank lines on some platforms.
flowchart TD
A[Choose mode] --> B{Keep old content?}
B -->|No| C["w: replace"]
B -->|Yes| D["a: append"]
C --> E[Write UTF-8 text]
D --> EWorking with paths using pathlib
pathlib.Path represents a filesystem path. The / operator joins path parts without manually choosing / or \ for an operating system.
from pathlib import Path
path = Path("data") / "greeting.txt"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("héllo\n", encoding="utf-8")
print(path.read_text(encoding="utf-8"))mkdir(parents=True) creates missing parent directories. exist_ok=True avoids an error when the directory already exists. write_text() and read_text() are convenient alternatives to open() for whole text files.
Exercise
Which mode should you use to add a line without deleting existing content?
Show answer
Use append mode, "a", and include a trailing \n if the new text should start on its own line.