← Back to Chapters

Python OS Module

? Python OS Module

? Quick Overview

The os module in Python lets you interact with the operating system. You can work with files and folders, check and build paths, read and set environment variables, and even execute system commands directly from your Python programs.

? Key Concepts

  • OS interface: Use os to talk to the underlying operating system.
  • Working directory: Get and change where your script is currently “looking”.
  • File and directory management: Create, remove, and list folders and files.
  • Path operations: Build, inspect, and normalize file paths using os.path.
  • Environment variables: Access system-level configuration like PATH or HOME.
  • System commands: Run shell commands from Python using os.system() (with care!).

? Syntax and Theory

  • import os – imports the OS module.
  • os.name – returns the type of OS interface: e.g. 'posix' (Linux/macOS) or 'nt' (Windows).
  • os.getcwd() – returns the current working directory (CWD).
  • os.mkdir(path) / os.rmdir(path) – create or remove a directory.
  • os.listdir(path='.') – lists entries in a directory (files and folders).
  • os.path.join(a, b, ...) – joins path parts using the correct separator for the OS.
  • os.path.exists(path) – checks if a file or directory exists.
  • os.path.abspath(path) – returns the absolute version of a path.
  • os.path.basename(path) / os.path.dirname(path) – get the file name or its directory part.
  • os.environ – a mapping (like a dictionary) of environment variables.
  • os.system(command) – passes a string to the system shell for execution.

? Code Examples

? Importing the OS Module

? View Code Example
import os
print(os.name)          # 'posix', 'nt', etc.
print(os.getcwd())      # Current working directory

? File and Directory Operations

? View Code Example
import os

# Create a directory
os.mkdir("test_folder")

# Remove a directory (must be empty)
os.rmdir("test_folder")

# List contents of the current directory
print(os.listdir())

? Path Operations

? View Code Example
import os

print(os.path.join("folder", "file.txt"))   # folder/file.txt (OS-specific)
print(os.path.exists("folder/file.txt"))    # True or False
print(os.path.abspath("file.txt"))          # Absolute path
print(os.path.basename("/folder/file.txt")) # file.txt
print(os.path.dirname("/folder/file.txt"))  # /folder

? Environment Variables

? View Code Example
import os

# Get an environment variable
print(os.environ.get("HOME"))

# Set an environment variable
os.environ["MY_VAR"] = "123"
print(os.environ.get("MY_VAR"))

⚡ Executing System Commands

? View Code Example
import os

# Run a simple system command
os.system("echo Hello World")

? Live Output / Explanation

? What You’ll See

  • os.name prints a short code for your OS, such as 'posix' or 'nt'.
  • os.getcwd() prints the current working directory where Python is running.
  • os.listdir() returns a list (like ['file1.py', 'folder']) of names in that directory.
  • os.path.exists() returns True if the path is valid, otherwise False.
  • os.environ.get("HOME") prints the value of your HOME (or similar) environment variable.
  • os.system("echo Hello World") will display Hello World in the console and return an exit status code (often 0 for success).

Exact outputs will vary depending on your operating system, current directory, and which files and environment variables exist on your machine.

? Use Cases

  • Building scripts that clean up or organize files and folders.
  • Writing tools that depend on configuration from environment variables (API keys, modes, etc.).
  • Automating tasks like backups, log rotation, or running other programs.
  • Creating cross-platform utilities that handle file paths correctly on Windows, macOS, and Linux.

? Tips & Best Practices

  • Use os.getcwd() to confirm where your script is currently working from.
  • Always use os.path.join() instead of hardcoding path separators like / or \.
  • Check if files or directories exist with os.path.exists() before using them.
  • Be careful with os.system() – it executes shell commands and can be risky with user input.
  • Do not use os.rmdir() for non-empty folders; use shutil.rmtree() from the shutil module instead.
  • Never assume an environment variable exists; use os.environ.get("VAR_NAME") and handle the case where it returns None.
  • Prefer high-level libraries (like subprocess) over os.system() for complex command execution.

? Try It Yourself

  • Create a folder called "my_folder" using os.mkdir(), verify it exists, then delete it.
  • List all files and folders in your current working directory with os.listdir().
  • Check if a file named "data.txt" exists using os.path.exists().
  • Print the absolute path of "data.txt" using os.path.abspath().
  • Set an environment variable called "TEST_VAR" and print its value.
  • Build a small script that prints your OS type, current directory, and the number of items in that directory.