Skip to main content
The os module provides a portable way to interact with the operating system, including file operations, process management, and environment variables.

Module Import

File and Directory Operations

Current Directory

Listing Directory Contents

os.scandir() - Efficient Directory Iteration

os.walk() - Recursive Directory Traversal

File Operations

Creating and Removing Files

File Information

Path Manipulation (os.path)

Joining Paths

Path Components

Path Properties

Environment Variables

os.environ

Dictionary of environment variables.

os.getenv() and os.putenv()

Process Management

Current Process

Running Commands

File Descriptors

Low-Level File Operations

File Descriptor Operations

Permissions and Ownership

File Permissions

Ownership (Unix only)

Platform-Specific

Path Separators

Special Paths

Practical Examples

Find All Files with Extension

Get Directory Size

Create Backup with Timestamp

Safe File Operations

Best Practices

Use pathlib for modern path handling: For new code, consider using pathlib.Path instead of os.path:
Be careful with os.remove(): It permanently deletes files without moving them to trash. Always verify the path before removing.
Use os.path.join() for cross-platform paths: Always use os.path.join() instead of string concatenation with / or \\.

Migration to pathlib

Many os and os.path functions have pathlib equivalents:

pathlib

Object-oriented filesystem paths

shutil

High-level file operations

glob

Unix-style pathname pattern expansion

tempfile

Temporary files and directories