Introduction
Pathlib provides object-oriented filesystem paths, cleaner than os.path.
Basic Path Operations
from pathlib import Path
p = Path(".")
# Traversing
p / "subdir" / "file.txt"
# Reading and writing
p.write_text("Hello")
content = p.read_text()
# Glob patterns
list(p.glob("*.py"))
list(p.glob("**/*.txt"))
Path Properties
from pathlib import Path
p = Path("example.txt")
p.name # 'example.txt'
p.stem # 'example'
p.suffix # '.txt'
p.parent # Parent directory
p.parts # Path components
p.exists()
p.is_file()
p.is_dir()
Creating Paths
from pathlib import Path
# Absolute paths
Path("/home/user/file")
Path.cwd() # Current working directory
Path.home() # Home directory
# Home-relative
Path("~/documents").expanduser()
Practice Problems
- Navigate directory tree with pathlib
- Find all Python files recursively
- Create file backup with new extension
- Walk directory hierarchy
- Resolve file paths safely