By the end of this lesson
Use pathlib and exclusive creation for an output file.
Before you start
- Python 3.12 or a compatible newer Python 3 interpreter; no external packages.
- Complete lesson 14 in this route, or be comfortable with its examples.
Three words to know
- Path
- A representation of a file or folder location.
- Encoding
- The rule used to translate bytes into text.
- Context manager
- A with block that performs cleanup when leaving its body.
1. A relative path starts in the working folder
Python does not assume that a data file lives next to the script. A relative path is resolved from the current working directory. Use a small practice folder so the intended file is easy to locate. The fixture below creates a new notes.txt only; if it already exists, choose a fresh folder or another filename.
from pathlib import Path
path = Path("notes.txt")
with path.open("x", encoding="utf-8") as handle:
handle.write("Read\nTest\n")
text = path.read_text(encoding="utf-8")
print(text, end="")
print(len(text.splitlines()))
What you should see · example output
Read Test 2
2. Select the write mode intentionally
Mode x creates a new file and fails if the name already exists. Mode w truncates an existing file; mode a appends. That distinction is important even for a short script. with closes the file when the block ends, including when an exception is raised. A downloaded file is not executed merely by reading or saving it.
3. Text is decoded bytes
Always state encoding="utf-8" when a format requires UTF-8. Missing files, permissions and invalid encoding are different failures. Do not silently ignore decoding errors when validating a format. read_text is convenient for a small trusted file, but it reads the whole file; a later project demonstrates a bounded byte read.
YOUR TURN
A small check before you continue
Run the file-creation example twice in the same folder. Why does the second run fail, and what should you do to preserve the first file?
Show a suggested answer
The x mode raises FileExistsError. Inspect the existing file, use a fresh practice folder or choose a new output name. Do not switch to w merely to silence the error if the existing content matters.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
