Skip to content

The os Module - Navigating Directories

diagram os.walk hands you a list you are meant to edit mermaid
Each step yields the current directory, its subdirectories and its files. The subdirectory list is not just information -- with the default top-down walk, os.walk reads it again after your loop body to decide where to go next. Removing an entry from it in place is how you skip a whole subtree, which is the difference between a script that finishes and one that walks into node_modules.

The os module provides:

  • current working directory
  • directory listing
  • environment variables
  • basic path manipulation (but prefer pathlib for paths)
cwd.py
import os
 
print(os.getcwd())
listdir.py
import os
 
for name in os.listdir("."):
    print(name)
chdir.py
import os
 
os.chdir("/tmp")
print(os.getcwd())
env_vars.py
import os
 
print(os.environ.get("HOME"))

For paths, use pathlib.Path whenever possible.

Exercise 2 – Join Paths with os.path.join

Section titled “Exercise 2 – Join Paths with os.path.join”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading