Skip to content

Module 15 · Python Standard Libraries — topic 5 of 13

os

Talking to the operating system with os: environment variables, the working directory, listing and scanning folders, creating and removing files and directories, walking trees, and portable path helpers.

Beginner 10 min read·Lesson 226 of 306 in Python Programming

Learning objectives

  • Read and set environment variables
  • Inspect and change directories
  • Scan folders efficiently with os.scandir and os.walk

Definition

The os module provides a portable interface to operating-system features: environment variables, process information, the current directory, and file and directory operations. os.path contains path utilities.

Introduction

Scripts often need to know where they are running, read configuration from the environment, or manage folders. os is the toolbox for that.

Why it matters

Environment variables are the standard way to configure applications and keep secrets out of code; os makes them easy to use.

Detailed explanation

os.environ is a dictionary-like mapping of environment variables; os.getenv("NAME", default) reads one safely. Setting os.environ["NAME"] affects this process and its children.

os.getcwd() returns the current working directory; os.chdir(path) changes it (affecting relative paths).

os.listdir(path) lists names; os.scandir(path) yields DirEntry objects with is_file(), is_dir() and stat() — faster when you need details.

os.makedirs creates nested folders, os.remove deletes files, os.rmdir deletes empty folders, os.rename and os.replace rename.

os.walk(top) visits every folder in a tree, yielding (folder, subfolders, files).

os.name is "nt" on Windows and "posix" elsewhere; os.sep is the path separator; os.cpu_count() reports processor cores.

For paths, pathlib is often clearer, but os and os.path remain common in existing code.

Syntax

Python
import os
api_key = os.getenv("API_KEY", "")
print(os.getcwd())
for entry in os.scandir("."):
print(entry.name, entry.is_dir())
  • getenv for configuration.
  • scandir for detailed listings.
  • walk for whole trees.

Code examples

Environment variables

Python
import os
os.environ["APP_MODE"] = "testing"
print(os.environ.get("APP_MODE"), os.environ.get("NOT_SET_VAR_123", "default"))
print(os.getenv("APP_MODE"))
Output
testing default
testing

Folders and the working directory

Python
import os
os.makedirs("data/raw", exist_ok=True)
for n in ["a.txt", "b.csv"]:
open(os.path.join("data", n), "w", encoding="utf-8").close()
print(sorted(os.listdir("data")))
print(os.path.basename(os.getcwd()) != "", os.path.isdir("data/raw"))
Output
['a.txt', 'b.csv', 'raw']
True True

More examples

Scanning a folder tree

Python
import os
files = {"docs/a.txt": "hello", "docs/b.txt": "hi", "docs/img/logo.svg": "<svg/>"}
for rel, text in files.items():
os.makedirs(os.path.dirname(rel), exist_ok=True)
with open(rel, "w", encoding="utf-8") as f:
f.write(text)
with os.scandir("docs") as entries:
for e in sorted(entries, key=lambda e: e.name):
kind = "dir " if e.is_dir() else "file"
size = e.stat().st_size if e.is_file() else "-"
print(kind, e.name, size)
total = sum(os.path.getsize(os.path.join(root, f)) for root, _, fs in os.walk("docs") for f in fs)
print("total bytes:", total)
print(os.name in ("nt", "posix"))
Output
file a.txt 5
file b.txt 2
dir  img -
total bytes: 13
True

Step-by-step explanation

  • scandir returns entries that already know whether they are files or folders, avoiding extra system calls.
  • os.walk visits docs and docs/img, and the generator expression sums every file's size.
  • os.name lets code branch on the operating system when it must.

Expected output

Running “Scanning a folder tree” prints exactly:

TextOutput
file a.txt 5
file b.txt 2
dir img -
total bytes: 13
True

Practical applications

  • Reading DATABASE_URL or API keys from the environment.
  • Disk-usage reports and cleanup scripts.

Best practices

  • Configure apps with environment variables.
  • Use scandir for listings with details.
  • Prefer pathlib for path manipulation in new code.

Common mistakes

Hard-coding secrets

Avoid

API_KEY = "abc123secret"

Prefer

API_KEY = os.environ["API_KEY"]

Secrets in code leak through version control; the environment keeps them separate.

Relying on listdir order

Avoid

first = os.listdir("data")[0]

Prefer

first = sorted(os.listdir("data"))[0]

The order is arbitrary and differs between systems.

Important notes

  • os.system and os.popen run shell commands, but subprocess is the safer, more flexible choice.

Key takeaways

  • os.environ and getenv read configuration.
  • listdir, scandir and walk explore folders.
  • os provides portable OS operations.

Try it yourself

  1. 1
    Print every environment variable whose name starts with PY.
  2. 2
    Find the largest file under a folder using os.walk.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic