Python pathlib Exercises: Paths, Names, and Text Files
A path is more than a string. It has a parent, a name, a suffix, and a platform-specific separator. pathlib gives those ideas names, so your code can say what it means instead of rebuilding paths with plus signs.
Join with the slash operator
Path('data') / 'scores.csv' creates a new path. The slash is overloaded for joining, not division. Each component stays readable, and pathlib chooses the separator used by the current system.
from pathlib import Path
path = Path("data") / "scores.csv"
print(path.as_posix())
print(path.name)A path built from parts
Read the parts instead of splitting
name, stem, suffix, and parent cover most filename questions. stem removes only the last suffix, so archive.tar.gz has stem archive.tar and suffix .gz. This is predictable and avoids custom string parsing.
from pathlib import Path
path = Path("reports/2026-summary.txt")
print(path.stem)
print(path.suffix)
print(path.parent.as_posix())Useful path properties
Write and read UTF-8 text
write_text replaces the file and read_text returns its contents. Specify UTF-8 explicitly so the bytes do not depend on the operating system's default encoding. Use unlink to remove a temporary file.
from pathlib import Path
path = Path("pypractice-guide-note.txt")
path.write_text("hello\n", encoding="utf-8")
print(path.read_text(encoding="utf-8").strip())
path.unlink()A complete small-file round trip
Check before you read
exists, is_file, and is_dir answer different questions. A path can exist and still be a directory, so is_file is the right check before read_text. These checks can become stale, so handle the actual read error as well.
from pathlib import Path
path = Path("pypractice-guide-note.txt")
print(path.exists())
print(path.is_file())Ask specific questions
Use as_posix for portable output
str(path) uses the host separator, which is a backslash on Windows. When output must be identical everywhere, call as_posix(). Use the native form when you are passing a path back to the operating system.
from pathlib import Path
print((Path("data") / "scores.csv").as_posix())Stable forward slashes
Your practice checklist
- Build paths with / instead of string concatenation.
- Use name, stem, suffix, and parent for path parts.
- Pass encoding='utf-8' when reading or writing text.
- Check is_file before read_text when a path may be missing.
- Use as_posix() for stable output and native paths for file operations.
Common questions
Is pathlib available on Windows?
Yes. pathlib is part of the standard library and chooses the correct separator for the operating system.
Does write_text create parent directories?
No. The parent directory must already exist; create it first if needed.
Should I store paths as strings?
Use Path objects inside your program. Convert to a string only at an API boundary that requires one.
Practice pathlib
12 questions on joining paths, suffixes, parents, file checks, and UTF-8 text.
Keep reading: