Modules & Packages
os Module
Operating system interactions for files, processes, and environment
Interview: Common in system programming interviews and practical Python tasks
The os module provides functions for interacting with the operating system — file operations, directory navigation, environment variables, and process management. For new code, prefer pathlib for path operations, but os remains essential for environment variables, process control, and low-level OS interactions.
Key os Functions
- os.getcwd(): Get current working directory
- os.listdir(path): List directory contents (prefer pathlib.iterdir())
- os.mkdir/os.makedirs: Create directories (prefer pathlib.mkdir(parents=True))
- os.remove/os.rmdir: Delete files/empty directories
- os.rename: Rename files or directories
- os.walk(): Recursively traverse directory tree — yields (dirpath, dirnames, filenames)
Environment Variables
- os.environ: Dict-like object for environment variables
- os.getenv(key): Get environment variable with optional default —
os.getenv("API_KEY", "default") - os.environ[key]: Direct access — raises KeyError if not set
Prefer pathlib for Paths
For path operations, use pathlib.Path instead of os.path. It's more Pythonic: Path("data") / "file.txt" instead of os.path.join("data", "file.txt"). Use os for environment variables and process control.
Use Cases
Reading configuration from environment variables (12-factor apps)
Recursive file processing and directory traversal
Cross-platform file system operations
Build scripts and deployment automation
Setting up project directory structures programmatically
Common Mistakes
Using os.path.join instead of pathlib Path operator / — pathlib is cleaner and more Pythonic
Hardcoding path separators ("/" or "\\") — always use os.path.join or pathlib
Using os.remove without checking if file exists — raises FileNotFoundError
Not using exist_ok=True with os.makedirs — fails if directory already exists
Mixing os.path and pathlib in the same codebase — pick one approach and be consistent