On this page
  1. os
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Fast Directory Traversal with os.scandir()
  7. 2. Atomic File Replacement with os.replace()
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

os

Prev: optparse | Up: stdlib_module | Next: pathlib
Rel: pathlib, io, time, fileinput, stat
Ref: docs.python.org — os
Tags: #public #python3 #stdlib


Import

import os

Overview

Low-level operating system interface for environment variables, process state, permissions, file descriptors, and directory walking across POSIX and Windows. Prefer pathlib for path manipulation and subprocess for running external commands; reach for os when you need os.environ, os.scandir(), os.walk(), os.replace(), or process metadata.

Quick Start

import os

debug = os.getenv("DEBUG", "0") == "1"
cwd = os.getcwd()
cpu_count = os.cpu_count() or 1
assert isinstance(cwd, str) and cpu_count >= 1

Implementation Walkthrough

1. Fast Directory Traversal with os.scandir()

os.scandir() yields DirEntry objects that cache stat metadata from the OS directory listing, avoiding extra syscalls compared to os.listdir():

import os

def list_large_files(root: str, min_bytes: int = 1024) -> list[str]:
    found = []
    with os.scandir(root) as entries:
        for entry in entries:
            if entry.is_file(follow_symlinks=False) and entry.stat().st_size >= min_bytes:
                found.append(entry.name)
    return sorted(found)

2. Atomic File Replacement with os.replace()

Write to a sibling temporary file in the same directory and swap it into place atomically so readers never observe a half-written file:

import os
from pathlib import Path

def atomic_write(target: Path, content: str) -> None:
    tmp = target.with_suffix(target.suffix + ".tmp")
    tmp.write_text(content, encoding="utf-8")
    os.replace(tmp, target)  # atomic on POSIX and Windows (same filesystem)

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes