How to work with paths

Create portable paths

Path handles platform-specific separators. The / operator joins path components without string concatenation.

from pathlib import Path

project = Path.home() / "projects" / "demo"
config = project / "config.json"
print(project)
print(config.name, config.suffix)

Inspect the filesystem

Path methods distinguish existence and file type. Resolve can produce an absolute normalized path.

from pathlib import Path

path = Path("notes.txt")
print(path.exists())
print(path.is_file())
print(path.resolve())

Create directories

parents=True creates missing parent directories. exist_ok=True prevents an error when the directory already exists.

from pathlib import Path

output = Path("build") / "reports"
output.mkdir(parents=True, exist_ok=True)
(output / "summary.txt").write_text("Done\n", encoding="utf-8")

List matching files

glob() searches one path level according to a pattern; rglob() searches recursively.

from pathlib import Path

for path in Path(".").rglob("*.py"):
    print(path)

text = Path("summary.txt").read_text(encoding="utf-8") if Path("summary.txt").exists() else ""
print(text)