Managing Paths with pathlib
Why pathlib
Section titled “Why pathlib”pathlib gives you:
- operator-free path joining
- clear methods (
exists,is_file,mkdir,read_text) - cross-platform behavior
Common patterns
Section titled “Common patterns”from pathlib import Path
base = Path.home() / "Downloads"
print(base)
for f in base.iterdir():
if f.is_file():
print(f.name, f.suffix)Reading and writing
Section titled “Reading and writing”from pathlib import Path
p = Path("hello.txt")
p.write_text("hello\n", encoding="utf-8")
print(p.read_text(encoding="utf-8"))🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading