pathlib — Modern File Paths (PEP 428)
pathlib — Modern File Paths (PEP 428)
🎯 After reading this lesson
Once you finish this lesson, you will be able to confidently do the following 3 things.
- ▸✅ pathlib.Path as the modern replacement for os.path
- ▸✅ with open() context manager + explicit encoding
- ▸✅ Using the csv · json · yaml standard modules
Keep the learning goals as a checklist, and close the lesson once you can answer all of them.
pathlib — Code + Execution Results
pathlib.Path = OS-independent path handling. Standard library since Python 3.6+. os.path is the old way.
1. Creating Paths
Join paths with the / operator — separators are handled automatically per OS.
2. Extracting Information
3. File Operations
4. Directory Operations
5. Comparison with os.path
One-line Summary
Path(...) / "..." + .read_text() + .glob() — these three cover 90% of use cases. Graduate from os.path.
🐍 Try It Yourself — pathlib — Run It Directly
🤖 Try Asking AI Like This
Knowing the concepts from this lesson lets you give specific instructions to AI. Instead of a vague "fix this," make a vocabulary-driven request — that is the starting point for saving tokens.
- ▸"Migrate this os.path code to pathlib"
- ▸"Add explicit encoding (encoding='utf-8') to this with open block"
Why This Reduces Tokens
When you don't know the concepts, you have to ask "What is that?" after receiving an AI response. That follow-up question is what consumes tokens. Learn the concept once, and the conversation ends in a single round.