Python Best Practices

Chapter 2 · Practice 4 of 5

Use pathlib for paths and name the encoding when you open text

From Style, formatting and linting

Why it matters

String paths joined with + or os.path.join break on Windows and are hard to read. pathlib.Path handles separators and gives you .read_text(), .glob() and .with_suffix() on the path itself.

Encoding is the other quiet bug. Before 3.15, open(path) used the locale encoding, so the same code read a file differently on Windows and Linux. Python 3.15 makes UTF-8 the default regardless of locale (PEP 686), but code that also runs on older versions should still pass encoding="utf-8" explicitly.

python
from pathlib import Path

config = Path(__file__).parent / "config" / "app.toml"
text = config.read_text(encoding="utf-8")