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
| API | Role |
|---|---|
os.environ | Mapping 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.sep | Platform hints |
os.listdir(path) | Directory entries (names only) |
os.makedirs(path, exist_ok=True) | Create dirs |
os.remove / os.rename | File ops |
os.path.join / exists / splitext | String path helpers |
pathlib.Path | Preferred 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"] # unsetCwd 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"]raisesKeyError— prefergetenv/.get.- Env values are always strings; cast (
int(os.getenv("PORT", "8000"))). chdiris process-global and surprises libraries — avoid in libraries.- Mixing
strandPathis fine at the boundary; stick to one style inside a module. listdirdoes not recurse; usePath.rgloboros.walkfor trees.