Python Central HubSign in

Automation and Scripting / Phase 1: OS & File System Automation

The os Module - Navigating Directories

Use os to inspect directories, change the working directory, and work with environment variables.

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.

What os is for

The os module provides:

  • current working directory
  • directory listing
  • environment variables
  • basic path manipulation (but prefer pathlib for paths)

Current working directory

Python
import os
 
print(os.getcwd())

List files

Python
import os
 
for name in os.listdir("."):
    print(name)

Change directory

Python
import os
 
os.chdir("/tmp")
print(os.getcwd())

Environment variables

Python
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

exerciseYour turn

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

exerciseYour turn

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

exerciseYour turn

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.

Was this page helpful?

Let us know how we did