The os Module - Navigating Directories
flowchart TD
A["os.walk('.')"] --> B["yield (root, dirs, files)"]
B --> C["your loop body runs"]
C --> D{"did you modify dirs IN PLACE?"}
D -->|"dirs.remove('b')"| E["that subtree is never visited"]
D -->|"dirs = [...] -- rebinding"| F["no effect; the walker still has the old list"]
D -->|no| G["descend into every subdirectory"]
E --> H["next root"]
G --> H
H --> B
I["topdown=False"] --> J["children first -- pruning no longer works"]
What os is for
Section titled “What os is for”The os module provides:
- current working directory
- directory listing
- environment variables
- basic path manipulation (but prefer
pathlibfor paths)
Current working directory
Section titled “Current working directory”import os
print(os.getcwd())List files
Section titled “List files”import os
for name in os.listdir("."):
print(name)Change directory
Section titled “Change directory”import os
os.chdir("/tmp")
print(os.getcwd())Environment variables
Section titled “Environment variables”import os
print(os.environ.get("HOME"))For paths, use pathlib.Path whenever possible.
🧪 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