OS Module

Advanced PythonSystemFree Lesson

Advertisement

Introduction

The OS module provides portable ways to interact with the operating system.

File System Operations

import os

# Paths
os.getcwd()           # Current directory
os.chdir("/path")     # Change directory
os.path.join("a", "b")  # Join paths

# File operations
os.remove("file.txt")
os.rename("old", "new")
os.mkdir("dir")
os.makedirs("a/b/c")  # Create nested dirs
os.rmdir("dir")       # Remove empty dir

# Check existence
os.path.exists("file.txt")
os.path.isfile("file.txt")
os.path.isdir("dir")

Directory Contents

import os

# List directory
os.listdir(".")

# Walk directory tree
for root, dirs, files in os.walk("."):
    print(root, dirs, files)

Environment and Process

import os

# Environment variables
os.environ["HOME"]
os.getenv("PATH")

# Process info
os.getpid()           # Current process ID
os.getuid()           # User ID
os.system("ls")       # Run shell command

Practice Problems

  1. Recursively list all files
  2. Find files matching pattern
  3. Create directory structure
  4. Get file metadata
  5. Walk directory with filtering

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement