OS Module: Work with the Operating System
Introduction
In this chapter, you will learn Python's os module, which helps your program interact with the operating system. With os, you can read environment information, manage paths, create folders, and inspect files. This is a foundational skill for automation scripts, tooling, and backend tasks.
Prerequisites
- Python
3.10+installed - Basic understanding of files, strings, and exception handling
- Ability to run
.pyfiles in terminal or IDE
What Is the os Module
os is a built-in Python module for OS-related operations.
Common use cases:
- get current working directory
- create/remove directories
- check file existence
- read environment variables
- iterate directory contents
1) Basic Environment Info
import os
# Current working directory
print(os.getcwd())
# Current OS name (e.g. 'nt' on Windows, 'posix' on Linux/macOS)
print(os.name)This is useful when debugging path issues.
2) Path Operations with os.path
os.path provides cross-platform path utilities.
import os
base_dir = os.getcwd()
file_path = os.path.join(base_dir, "data", "report.txt")
print(file_path)
print(os.path.exists(file_path))
print(os.path.dirname(file_path))
print(os.path.basename(file_path))Using os.path.join() is safer than manual string concatenation.
Tip
Best Practice
Always build paths with os.path.join() for cross-platform compatibility.
3) Directory Management
import os
# Create one directory
os.mkdir("logs")
# Create nested directories
os.makedirs("output/reports/2026", exist_ok=True)
# Rename directory
os.rename("logs", "app_logs")
# Remove empty directory
os.rmdir("app_logs")Use exist_ok=True to avoid errors when directory already exists.
4) List and Traverse Files
import os
# List current directory entries
items = os.listdir(".")
print(items)
# Walk through directory tree
for root, dirs, files in os.walk("."):
print("Root:", root)
print("Dirs:", dirs)
print("Files:", files)
break # remove break to traverse fullyos.walk() is useful for batch processing and project scanning.
5) Environment Variables
Use environment variables for configuration and secrets access.
import os
# Read environment variable
python_path = os.getenv("PYTHONPATH")
print("PYTHONPATH:", python_path)
# Read with default value
app_mode = os.getenv("APP_MODE", "dev")
print("APP_MODE:", app_mode)This pattern is common in deployment and CI/CD scripts.
6) Real Mini Example: Folder Report Generator
This script lists files in a target folder and saves summary to a text report.
import os
target_dir = "."
report_file = "folder_report.txt"
files = []
dirs = []
# Collect top-level entries
for item in os.listdir(target_dir):
full_path = os.path.join(target_dir, item)
if os.path.isdir(full_path):
dirs.append(item)
else:
files.append(item)
# Write report
with open(report_file, "w", encoding="utf-8") as f:
f.write("=== Folder Report ===\n")
f.write(f"Target directory: {os.path.abspath(target_dir)}\n\n")
f.write("Directories:\n")
for d in dirs:
f.write(f"- {d}\n")
f.write("\nFiles:\n")
for file_name in files:
f.write(f"- {file_name}\n")
print(f"Report generated: {report_file}")This is a practical building block for automation tools.
Warning
Operations like rename/remove can change or delete data.
Always verify target paths before destructive file-system actions.
Common Beginner Mistakes
Mistake 1: Hardcoding Path Separators
Using "/" or "\\" manually can cause cross-platform issues.
Mistake 2: Not Checking Existence Before Actions
Calling remove/rename on missing paths raises errors.
Mistake 3: Using Relative Paths Without Understanding CWD
Scripts may run from different working directories, causing path confusion.
Surprise Practice Challenge
Build a "Project Cleaner":
- Traverse a target folder
- Find files ending with
.tmpor.log - Print detected file list
- Ask user to confirm deletion
- Delete confirmed files and print summary
If you finish this, you can build practical filesystem automation scripts.
FAQ
Should I use os or pathlib?
Both are valid. pathlib is often more modern and object-oriented, while os is classic and widely used.
Why does my script find files in unexpected places?
Usually because current working directory is different from what you expect.
Can os.remove() delete directories?
No. os.remove() is for files. Use os.rmdir() for empty directories.
Is os.walk() expensive?
It can be, on large directories. Add filters and stop conditions when possible.