Code Reference

OS

Python · Reference cheat sheet

OS

Python · Reference cheat sheet


📋 Overview

The os module talks to the operating system: env vars, process info, and basic path helpers. Prefer pathlib for path work; keep os for env, cwd, and platform details.

🔧 Core concepts

APIRole
os.environMapping of environment variables
os.getenv(k, default)Safe read (returns None / default)
os.environ["KEY"]Read/set; KeyError if missing
os.getcwd() / os.chdir(path)Working directory
os.name / os.sepPlatform hints
os.listdir(path)Directory entries (names only)
os.makedirs(path, exist_ok=True)Create dirs
os.remove / os.renameFile ops
os.path.join / exists / splitextString path helpers
pathlib.PathPreferred OO paths

os.path vs pathlib: os.path returns strings; Path objects support /, .read_text(), .glob(), and clearer APIs. Use pathlib for new code; os.path still appears in older APIs.

💡 Examples

Environment variables:

import os

home = os.getenv("HOME") or os.getenv("USERPROFILE")
os.environ["APP_ENV"] = "dev"
print(os.environ.get("APP_ENV", "prod"))
# del os.environ["APP_ENV"]  # unset

Cwd and listing:

import os
from pathlib import Path

print(os.getcwd())
for name in os.listdir("."):
    print(name, Path(name).is_file())

os.path vs pathlib:

import os
from pathlib import Path

s = os.path.join("data", "a.csv")
print(os.path.exists(s), os.path.splitext(s))

p = Path("data") / "a.csv"
print(p.exists(), p.suffix, p.read_text(encoding="utf-8") if p.exists() else "")

Create dirs (os vs pathlib):

import os
from pathlib import Path

os.makedirs("out/logs", exist_ok=True)
Path("out/cache").mkdir(parents=True, exist_ok=True)

⚠️ Pitfalls

  • os.environ["MISSING"] raises KeyError — prefer getenv / .get.
  • Env values are always strings; cast (int(os.getenv("PORT", "8000"))).
  • chdir is process-global and surprises libraries — avoid in libraries.
  • Mixing str and Path is fine at the boundary; stick to one style inside a module.
  • listdir does not recurse; use Path.rglob or os.walk for trees.

On this page