os

chevron-rightmethodshashtag

os (Standard Library for OS Operations)

pythonCopyEditimport os
Function/Property
Description

os.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

chevron-rightexamplehashtag

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

First, import the module:

import os

🔹 os.getenv()Access AWS Credentials from Env

aws_key = os.getenv("AWS_ACCESS_KEY_ID")
print("AWS Key:", aws_key)

📌 Use in automation scripts to securely read secrets/vars.


🔹 os.environSet Temporary Env Var

os.environ["ENV"] = "production"
print("ENV:", os.environ["ENV"])

📌 Useful for CI/CD jobs or subprocesses.


🔹 os.path.exists()Check If Config File Exists

if os.path.exists("/etc/nginx/nginx.conf"):
    print("Nginx config found")

📌 Use before applying configs or restarts.


🔹 os.path.join()Build File Paths Safely

path = os.path.join("/var/log", "app", "error.log")
print(path)

✅ Avoids OS-specific path bugs.


🔹 os.listdir()List Backup Files

files = os.listdir("/backups")
print("Backup files:", files)

📌 Handy for cleanup, audits, and automation.


🔹 os.remove()Delete Old Log File

os.remove("/tmp/old.log")
print("Old log deleted")

⚠️ Be cautious; it deletes immediately.


🔹 os.rename()Rotate Log File

os.rename("app.log", "app.log.1")
print("Log rotated")

📌 Used in log rotation or temp file handling.


🔹 os.mkdir() / os.makedirs()Create Directories

os.makedirs("/tmp/devops/logs", exist_ok=True)
print("Directories created")

makedirs() creates all intermediate folders.


🔹 os.rmdir() / os.removedirs()Remove Directories

os.rmdir("/tmp/test")
os.removedirs("/tmp/devops/logs")

📌 Use in teardown or cleanup scripts.


🔹 os.system()Execute Shell Command

os.system("systemctl restart nginx")

⚠️ Avoid in untrusted input cases — use subprocess instead for security.


🔹 os.path.basename()Get Filename from Path

print(os.path.basename("/var/log/nginx/error.log"))
# Output: error.log

📌 Used in logs and reports.


🔹 os.path.abspath()Get Absolute Path

print(os.path.abspath("deploy.sh"))

✅ Use for clarity and robustness in scripts.


🔹 os.chmod()Set File Permissions

os.chmod("script.sh", 0o755)

📌 Automate deploy scripts with correct permissions.


🔹 os.getcwd()Get Current Directory

print("Current working directory:", os.getcwd())

📌 Useful in debugging or directory-aware scripts.


🔹 os.chdir()Switch Working Directory

os.chdir("/var/www")
print("Switched to:", os.getcwd())

📌 Use in deploy scripts to ensure correct context.


🔹 os.walk()Recursive Directory Traversal

for 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

info = os.stat("app.log")
print(f"Size: {info.st_size} bytes | Modified: {info.st_mtime}")

📌 Use for log monitoring, age-based cleanup.


✅ Summary Table

Function / Property
DevOps/SRE Use Case

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 + os Let me know!

Last updated