Reading preferences
Concept

Paths and Filesystem Operations

Build paths, read text, and understand when filesystem operations can fail.

python, pathlib, paths, files, directories

A path is a location, not the file

pathlib.Path represents a filesystem path. Joining components does not create anything. A relative path depends on the current working directory, which may differ from the directory containing a Python source file.

Python illustration

Assume the working directory contains a UTF-8 file notes/today.txt with Read followed by a newline:

from pathlib import Path

folder = Path("notes")
note = folder / "today.txt"
print(note.name)
print(note.suffix)
print(note.read_text(encoding="utf-8").strip())

Prepared output — not live execution:

today.txt
.txt
Read

read_text opens and closes the file; strip changes the returned string, not the file. Missing files, permissions, and decoding problems can raise different exceptions.

See the reasoning

Follow the example one step at a time

Follow path construction and reading the prepared text file. This is a prepared teaching demonstration, not live code execution.

Construct a folder path

folder → Path("notes")

This creates a path object; it does not create the directory.

Creating and changing files

Path("notes").mkdir(parents=True, exist_ok=True) creates missing directories and accepts an existing directory; it does not ignore every error. Path.iterdir() lists children in an unspecified order. write_text can overwrite an existing file; for exclusive creation use path.open("x", encoding="utf-8"). rename and unlink change or remove filesystem entries and can lose data. Use them only on intended paths with permission and explicit error handling.

An exists() check is not a guarantee that a later read or write will succeed: the filesystem may change between operations. Handle failure at the operation itself. Do not assume path resolution alone makes an untrusted path safe; access boundaries and symbolic links require careful design.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does Path("notes") / "today.txt" construct?
2. Where is a relative path resolved?
3. What does mkdir with parents=True and exist_ok=True permit?
4. Why must a program still handle errors after checking that a path exists?

References and further reading