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
The os module provides:
- current working directory
- directory listing
- environment variables
- basic path manipulation (but prefer
pathlibfor paths)
Current working directory
import os
print(os.getcwd())List files
import os
for name in os.listdir("."):
print(name)Change directory
import os
os.chdir("/tmp")
print(os.getcwd())Environment variables
import os
print(os.environ.get("HOME"))Notes
For paths, use pathlib.Path whenever possible.
๐งช Try It Yourself
Exercise 1 โ List Files with os.listdir
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 2 โ Join Paths with os.path.join
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 3 โ Write and Read a File
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.