Introduction
The OS module provides portable ways to interact with the operating system.
File System Operations
import os
# Paths
os.getcwd() # Current directory
os.chdir("/path") # Change directory
os.path.join("a", "b") # Join paths
# File operations
os.remove("file.txt")
os.rename("old", "new")
os.mkdir("dir")
os.makedirs("a/b/c") # Create nested dirs
os.rmdir("dir") # Remove empty dir
# Check existence
os.path.exists("file.txt")
os.path.isfile("file.txt")
os.path.isdir("dir")
Directory Contents
import os
# List directory
os.listdir(".")
# Walk directory tree
for root, dirs, files in os.walk("."):
print(root, dirs, files)
Environment and Process
import os
# Environment variables
os.environ["HOME"]
os.getenv("PATH")
# Process info
os.getpid() # Current process ID
os.getuid() # User ID
os.system("ls") # Run shell command
Practice Problems
- Recursively list all files
- Find files matching pattern
- Create directory structure
- Get file metadata
- Walk directory with filtering