System Operations with os & sys

The os and sys modules provide crucial tools for interacting with the operating system and Python runtime environment.

os Module Essentials

File System Operations

# Get current directory
cwd = os.getcwd()
# List directory contents
files = os.listdir()

Path Manipulation

# Platform-independent paths
config_path = os.path.join("etc", "app", "config.ini")

sys Module Features

Runtime Information

# Python version
version = sys.version.split()[0]
# Command-line arguments
script_name = sys.argv[0]

Standard I/O

# Write to stderr
sys.stderr.write("Error message\n")

Common Pitfalls

# Hardcoding path separators
bad_path = "etc\\app\\config.ini" # Non-portable
# Not checking file existence
os.listdir("nonexistent_dir") # FileNotFoundError

Practical Use: Configuration Loader

import sys
import os
def load_config():
config_path = os.path.join(os.getenv("HOME"), ".apprc")
if not os.path.exists(config_path):
sys.stderr.write(f"Missing config: {config_path}\n")
sys.exit(1)
# Load configuration...

Your Task: System Information Script

Create a script that reports system information:

  1. Get Python version from sys
  2. Retrieve user's home directory
  3. List first two files in current directory
  4. Construct a platform-safe file path
  5. Display executed script name
Section 1/5os Module Essentials

os Module Essentials

File System Operations

System Operations with os & sys

The os and sys modules provide crucial tools for interacting with the operating system and Python runtime environment.

os Module Essentials

File System Operations

# Get current directory
cwd = os.getcwd()
# List directory contents
files = os.listdir()

Path Manipulation

# Platform-independent paths
config_path = os.path.join("etc", "app", "config.ini")

Output:

Click "Check" to run your code.