Lesson 24: Working with the OS and System Commands

How Python interacts with your operating system and executes system-level tasks

Why Work with the OS?

Many automation and scripting tasks require interacting with the operating system. Python provides built‑in modules to manage files, directories, environment variables, and even run system commands.

The os Module

The os module gives you access to many OS‑level operations.

Getting the Current Working Directory

import os

print(os.getcwd())

Listing Files

files = os.listdir(".")
print(files)

Creating and Removing Directories

os.mkdir("new_folder")
os.rmdir("new_folder")

Working with File Paths

Use os.path to build safe, cross‑platform paths:

path = os.path.join("folder", "file.txt")
print(path)

Environment Variables

Environment variables store configuration outside your code.

import os

api_key = os.getenv("API_KEY")
print(api_key)

Running System Commands

Use os.system() for simple commands:

os.system("echo Hello")

The subprocess Module

subprocess is more powerful and secure than os.system().

Running a Command and Capturing Output

import subprocess

result = subprocess.run(["echo", "Hello"], capture_output=True, text=True)
print(result.stdout)

Running a Python Script

subprocess.run(["python", "script.py"])

Error Handling with subprocess

try:
    subprocess.run(["ls", "nonexistent"], check=True)
except subprocess.CalledProcessError:
    print("Command failed!")

Why OS Interaction Matters

Next Steps

Now that you can interact with the operating system, you're ready to explore how Python works with files and data formats in Lesson 25: Working with CSV and Excel Files.

← Back to Lesson Index