os
methods
✅ os (Standard Library for OS Operations)
os (Standard Library for OS Operations)pythonCopyEditimport osos.getenv()
Get environment variable
os.environ
Dict of environment variables
os.path.exists()
Check if file/path exists
os.path.join()
Join file paths
os.listdir()
List files in directory
os.remove()
Delete file
os.rename()
Rename file or directory
os.mkdir() / os.makedirs()
Create directory (single/all levels)
os.rmdir() / os.removedirs()
Remove directory
os.system()
Run shell command
os.path.basename()
Get filename from path
os.path.abspath()
Get absolute path
os.chmod()
Change permission of file
os.getcwd()
Get current working directory
os.chdir()
Change current working directory
os.walk()
Recursively traverse directory structure
os.stat()
Get file metadata
example
Here’s a DevOps/SRE-centric guide for Python's os module, with real-world examples for each function/property — ideal for scripts managing environments, files, directories, and shell tasks.
✅ os — Python Standard Library for OS Operations
os — Python Standard Library for OS OperationsFirst, import the module:
import os🔹 os.getenv() — Access AWS Credentials from Env
os.getenv() — Access AWS Credentials from Envaws_key = os.getenv("AWS_ACCESS_KEY_ID")
print("AWS Key:", aws_key)📌 Use in automation scripts to securely read secrets/vars.
🔹 os.environ — Set Temporary Env Var
os.environ — Set Temporary Env Varos.environ["ENV"] = "production"
print("ENV:", os.environ["ENV"])📌 Useful for CI/CD jobs or subprocesses.
🔹 os.path.exists() — Check If Config File Exists
os.path.exists() — Check If Config File Existsif os.path.exists("/etc/nginx/nginx.conf"):
print("Nginx config found")📌 Use before applying configs or restarts.
🔹 os.path.join() — Build File Paths Safely
os.path.join() — Build File Paths Safelypath = os.path.join("/var/log", "app", "error.log")
print(path)✅ Avoids OS-specific path bugs.
🔹 os.listdir() — List Backup Files
os.listdir() — List Backup Filesfiles = os.listdir("/backups")
print("Backup files:", files)📌 Handy for cleanup, audits, and automation.
🔹 os.remove() — Delete Old Log File
os.remove() — Delete Old Log Fileos.remove("/tmp/old.log")
print("Old log deleted")⚠️ Be cautious; it deletes immediately.
🔹 os.rename() — Rotate Log File
os.rename() — Rotate Log Fileos.rename("app.log", "app.log.1")
print("Log rotated")📌 Used in log rotation or temp file handling.
🔹 os.mkdir() / os.makedirs() — Create Directories
os.mkdir() / os.makedirs() — Create Directoriesos.makedirs("/tmp/devops/logs", exist_ok=True)
print("Directories created")✅ makedirs() creates all intermediate folders.
🔹 os.rmdir() / os.removedirs() — Remove Directories
os.rmdir() / os.removedirs() — Remove Directoriesos.rmdir("/tmp/test")
os.removedirs("/tmp/devops/logs")📌 Use in teardown or cleanup scripts.
🔹 os.system() — Execute Shell Command
os.system() — Execute Shell Commandos.system("systemctl restart nginx")⚠️ Avoid in untrusted input cases — use subprocess instead for security.
🔹 os.path.basename() — Get Filename from Path
os.path.basename() — Get Filename from Pathprint(os.path.basename("/var/log/nginx/error.log"))
# Output: error.log📌 Used in logs and reports.
🔹 os.path.abspath() — Get Absolute Path
os.path.abspath() — Get Absolute Pathprint(os.path.abspath("deploy.sh"))✅ Use for clarity and robustness in scripts.
🔹 os.chmod() — Set File Permissions
os.chmod() — Set File Permissionsos.chmod("script.sh", 0o755)📌 Automate deploy scripts with correct permissions.
🔹 os.getcwd() — Get Current Directory
os.getcwd() — Get Current Directoryprint("Current working directory:", os.getcwd())📌 Useful in debugging or directory-aware scripts.
🔹 os.chdir() — Switch Working Directory
os.chdir() — Switch Working Directoryos.chdir("/var/www")
print("Switched to:", os.getcwd())📌 Use in deploy scripts to ensure correct context.
🔹 os.walk() — Recursive Directory Traversal
os.walk() — Recursive Directory Traversalfor dirpath, dirs, files in os.walk("/var/log"):
for file in files:
print(os.path.join(dirpath, file))📌 Use for backups, audits, or large cleanups.
🔹 os.stat() — Get File Metadata
os.stat() — Get File Metadatainfo = os.stat("app.log")
print(f"Size: {info.st_size} bytes | Modified: {info.st_mtime}")📌 Use for log monitoring, age-based cleanup.
✅ Summary Table
os.getenv()
Read secrets or config from env vars
os.environ
Set variables for scripts or subprocesses
os.path.exists()
Check config/log presence
os.path.join()
Build platform-safe paths
os.listdir()
List log or backup files
os.remove()
Delete old files/logs
os.rename()
Rotate or move files
os.mkdir() / makedirs()
Create deploy or backup folders
os.rmdir() / removedirs()
Teardown or cleanup directories
os.system()
Run shell commands (e.g., service restart)
os.path.basename()
Extract filenames for reports
os.path.abspath()
Normalize paths
os.chmod()
Set script permissions
os.getcwd()
Get script context
os.chdir()
Change to deploy or log directory
os.walk()
Traverse entire directory tree
os.stat()
Fetch size, timestamps, etc.
Would you like:
🖼️ A visual cheat sheet image
🧪 A ready Jupyter notebook
📘 A combined PDF for
requests + boto3 + yaml + json + osLet me know!
Last updated