- What is OS module — interacting with the operating system
- Directories — create, delete, list, change directories
- Files — create, rename, delete, check existence
- Paths — work with file paths (join, split, get extensions)
- Environment variables — get and set environment variables
- System info — get system information
What is OS Module?
The os module is Python's gateway to your operating system. It lets you interact with files, directories, environment variables, and system commands.
Think of the OS module like a remote control for your computer. You can use it to create folders, rename files, check what's in a directory, and even see what operating system you're using.
The OS module works on Windows, Mac, and Linux. The code you write will work on all operating systems (with some small differences).
💡 Key concept: The OS module gives you a way to interact with the operating system from your Python code.
Working with Directories
Create, Delete, List, and Change Directories
The OS module gives you full control over directories.
# Working with Directories
import os
print("=" * 50)
print("WORKING WITH DIRECTORIES")
print("=" * 50)
# ============================================================
# GET CURRENT DIRECTORY
# ============================================================
print("\n1. GET CURRENT DIRECTORY")
# Get current working directory
current_dir = os.getcwd()
print(f" Current directory: {current_dir}")
# ============================================================
# LIST DIRECTORY CONTENTS
# ============================================================
print("\n2. LIST DIRECTORY CONTENTS")
# List all files and folders in current directory
items = os.listdir('.')
print(f" Items in current directory: {items}")
# List with filter (only .py files)
py_files = [f for f in os.listdir('.') if f.endswith('.py')]
print(f" Python files: {py_files}")
# ============================================================
# CREATE DIRECTORY
# ============================================================
print("\n3. CREATE DIRECTORY")
# Create a single directory
os.mkdir("test_folder")
print(" Created: test_folder")
# Create nested directories
os.makedirs("test_folder/sub_folder/deep", exist_ok=True)
print(" Created: test_folder/sub_folder/deep")
# ============================================================
# CHANGE DIRECTORY
# ============================================================
print("\n4. CHANGE DIRECTORY")
# Change to a directory
os.chdir("test_folder")
print(f" Changed to: {os.getcwd()}")
# Change back
os.chdir("..")
print(f" Changed back to: {os.getcwd()}")
# ============================================================
# DELETE DIRECTORY
# ============================================================
print("\n5. DELETE DIRECTORY")
# Remove empty directory
os.rmdir("test_folder/sub_folder/deep")
print(" Removed: test_folder/sub_folder/deep")
# Remove nested directories
os.removedirs("test_folder/sub_folder")
print(" Removed: test_folder/sub_folder")
# Remove the main directory
os.rmdir("test_folder")
print(" Removed: test_folder")
# ============================================================
# WALK THROUGH DIRECTORIES
# ============================================================
print("\n6. WALK THROUGH DIRECTORIES")
# Create some test directories and files
os.makedirs("test_walk/a", exist_ok=True)
os.makedirs("test_walk/b", exist_ok=True)
with open("test_walk/a/file1.txt", "w") as f:
f.write("Hello")
with open("test_walk/b/file2.txt", "w") as f:
f.write("World")
# Walk through directories
print(" Directory structure:")
for root, dirs, files in os.walk("test_walk"):
print(f" {root}:")
for d in dirs:
print(f" Dir: {d}")
for f in files:
print(f" File: {f}")
# Clean up
import shutil
shutil.rmtree("test_walk")
print(" Cleaned up test_walk")
Directories key points:
- os.getcwd() — get current directory
- os.listdir() — list directory contents
- os.mkdir() — create a directory
- os.makedirs() — create nested directories
- os.chdir() — change directory
- os.walk() — walk through directory tree
Quick Check: How do you get the current working directory? (Answer: os.getcwd())
Working with Files
Create, Rename, Delete, and Check Files
The OS module helps you manage files on your system.
# Working with Files
import os
print("=" * 50)
print("WORKING WITH FILES")
print("=" * 50)
# ============================================================
# CHECK IF FILE EXISTS
# ============================================================
print("\n1. CHECK IF FILE EXISTS")
# Check if file exists
file_exists = os.path.exists("test.txt")
print(f" test.txt exists: {file_exists}")
# Check if it's a file
is_file = os.path.isfile("test.txt")
print(f" test.txt is a file: {is_file}")
# Check if it's a directory
is_dir = os.path.isdir("test.txt")
print(f" test.txt is a directory: {is_dir}")
# ============================================================
# CREATE A FILE
# ============================================================
print("\n2. CREATE A FILE")
# Create a file
with open("sample.txt", "w") as f:
f.write("Hello, World!")
print(" Created: sample.txt")
print(f" Exists: {os.path.exists('sample.txt')}")
# ============================================================
# GET FILE INFORMATION
# ============================================================
print("\n3. GET FILE INFORMATION")
# Get file size
size = os.path.getsize("sample.txt")
print(f" File size: {size} bytes")
# Get file modification time
import time
mod_time = os.path.getmtime("sample.txt")
print(f" Modified: {time.ctime(mod_time)}")
# Get file creation time
# Windows: getctime, Linux: getctime is change time
# Using pathlib is better for cross-platform
# ============================================================
# RENAME A FILE
# ============================================================
print("\n4. RENAME A FILE")
# Rename the file
os.rename("sample.txt", "renamed.txt")
print(" Renamed: sample.txt -> renamed.txt")
# Check if original exists
print(f" sample.txt exists: {os.path.exists('sample.txt')}")
print(f" renamed.txt exists: {os.path.exists('renamed.txt')}")
# ============================================================
# COPY A FILE (using shutil)
# ============================================================
print("\n5. COPY A FILE")
import shutil
# Copy the file
shutil.copy("renamed.txt", "copy.txt")
print(" Copied: renamed.txt -> copy.txt")
print(f" copy.txt exists: {os.path.exists('copy.txt')}")
# ============================================================
# DELETE A FILE
# ============================================================
print("\n6. DELETE A FILE")
# Delete files
os.remove("renamed.txt")
print(" Deleted: renamed.txt")
os.remove("copy.txt")
print(" Deleted: copy.txt")
# Check if they exist
print(f" renamed.txt exists: {os.path.exists('renamed.txt')}")
# ============================================================
# GET FILE EXTENSION
# ============================================================
print("\n7. GET FILE EXTENSION")
filename = "document.pdf"
name, ext = os.path.splitext(filename)
print(f" Filename: {filename}")
print(f" Name: {name}")
print(f" Extension: {ext}")
Files key points:
- os.path.exists() — check if file exists
- os.path.isfile() — check if it's a file
- os.path.isdir() — check if it's a directory
- os.rename() — rename a file
- os.remove() — delete a file
- os.path.splitext() — get file extension
Quick Check: How do you delete a file? (Answer: os.remove(filename))
Working with Paths
Join, Split, and Manipulate Paths
Working with file paths is easy with the OS module's path functions.
# Working with Paths
import os
print("=" * 50)
print("WORKING WITH PATHS")
print("=" * 50)
# ============================================================
# JOIN PATHS
# ============================================================
print("\n1. JOIN PATHS")
# Join path components
path1 = os.path.join("folder", "subfolder", "file.txt")
print(f" Joined path: {path1}")
# Works on any OS (Windows, Mac, Linux)
path2 = os.path.join("data", "images", "photo.jpg")
print(f" Another path: {path2}")
# With current directory
current_path = os.path.join(os.getcwd(), "file.txt")
print(f" Full path: {current_path}")
# ============================================================
# SPLIT PATH
# ============================================================
print("\n2. SPLIT PATH")
path = "/home/user/Documents/file.txt"
# Split directory and filename
dir_name, file_name = os.path.split(path)
print(f" Path: {path}")
print(f" Directory: {dir_name}")
print(f" Filename: {file_name}")
# Split extension
root, ext = os.path.splitext(path)
print(f" Root: {root}")
print(f" Extension: {ext}")
# ============================================================
# GET PATH COMPONENTS
# ============================================================
print("\n3. GET PATH COMPONENTS")
path = "/home/user/Documents/file.txt"
# Get directory name
dirname = os.path.dirname(path)
print(f" Directory name: {dirname}")
# Get base name (filename)
basename = os.path.basename(path)
print(f" Base name: {basename}")
# Get absolute path
abs_path = os.path.abspath("file.txt")
print(f" Absolute path: {abs_path}")
# ============================================================
# NORMALIZE PATH
# ============================================================
print("\n4. NORMALIZE PATH")
# Fix path issues
messy_path = "folder/./subfolder/../file.txt"
clean_path = os.path.normpath(messy_path)
print(f" Messy: {messy_path}")
print(f" Clean: {clean_path}")
# ============================================================
# CHECK PATH PROPERTIES
# ============================================================
print("\n5. CHECK PATH PROPERTIES")
path = "test.txt"
# Check if absolute
print(f" Is absolute: {os.path.isabs(path)}")
# Check if path exists
print(f" Exists: {os.path.exists(path)}")
# Check if it's a file
print(f" Is file: {os.path.isfile(path)}")
# Check if it's a directory
print(f" Is directory: {os.path.isdir(path)}")
# Check if it's a symbolic link
print(f" Is link: {os.path.islink(path)}")
Paths key points:
- os.path.join() — join path components
- os.path.split() — split directory and filename
- os.path.splitext() — split extension
- os.path.dirname() — get directory name
- os.path.basename() — get filename
- os.path.abspath() — get absolute path
Quick Check: How do you join two path components? (Answer: os.path.join("folder", "file.txt"))
Environment Variables
Get and Set Environment Variables
Environment variables are key-value pairs that your operating system uses to store information. You can access them with the OS module.
# Environment Variables
import os
print("=" * 50)
print("ENVIRONMENT VARIABLES")
print("=" * 50)
# ============================================================
# GET ENVIRONMENT VARIABLES
# ============================================================
print("\n1. GET ENVIRONMENT VARIABLES")
# Get a single variable (with default)
path = os.environ.get("PATH", "Not found")
print(f" PATH: {path[:50]}...")
# Get with default if not found
home = os.environ.get("HOME", "Not found")
print(f" HOME: {home}")
# Get without default (throws error if not found)
# python_path = os.environ["PYTHONPATH"]
# ============================================================
# GET ALL ENVIRONMENT VARIABLES
# ============================================================
print("\n2. GET ALL ENVIRONMENT VARIABLES")
# Get all environment variables
all_env = os.environ
print(" Some environment variables:")
count = 0
for key in list(all_env.keys())[:5]:
print(f" {key}: {all_env[key][:30]}...")
count += 1
print(f" ... and {len(all_env) - count} more")
# ============================================================
# SET ENVIRONMENT VARIABLES
# ============================================================
print("\n3. SET ENVIRONMENT VARIABLES")
# Set an environment variable
os.environ["MY_APP_CONFIG"] = "production"
print(f" Set MY_APP_CONFIG = {os.environ.get('MY_APP_CONFIG')}")
# Set another variable
os.environ["DEBUG"] = "True"
print(f" DEBUG = {os.environ.get('DEBUG')}")
# These variables will be available to subprocesses
# ============================================================
# CHECK IF VARIABLE EXISTS
# ============================================================
print("\n4. CHECK IF VARIABLE EXISTS")
print(f" MY_APP_CONFIG exists: {'MY_APP_CONFIG' in os.environ}")
print(f" NON_EXISTENT exists: {'NON_EXISTENT' in os.environ}")
# ============================================================
# DELETE ENVIRONMENT VARIABLE
# ============================================================
print("\n5. DELETE ENVIRONMENT VARIABLE")
# Delete a variable
if "MY_APP_CONFIG" in os.environ:
del os.environ["MY_APP_CONFIG"]
print(f" Deleted MY_APP_CONFIG")
print(f" MY_APP_CONFIG exists: {'MY_APP_CONFIG' in os.environ}")
# ============================================================
# COMMON ENVIRONMENT VARIABLES
# ============================================================
print("\n6. COMMON ENVIRONMENT VARIABLES")
# Common variables (different names on different OS)
def get_var(var_names, default="Not found"):
for name in var_names:
if name in os.environ:
return os.environ[name]
return default
# Try multiple possible names
user = get_var(["USER", "USERNAME"], "Unknown")
print(f" User: {user}")
# OS-specific variables
print(f" OS: {os.name}")
Environment variables key points:
- os.environ — dictionary of environment variables
- os.environ.get(key, default) — get with default
- os.environ[key] = value — set a variable
- del os.environ[key] — delete a variable
Quick Check: How do you get an environment variable with a default? (Answer: os.environ.get("KEY", "default"))
System Information
Get Information About Your System
The OS module can tell you about the operating system, the user, and the system resources.
# System Information
import os
print("=" * 50)
print("SYSTEM INFORMATION")
print("=" * 50)
# ============================================================
# OPERATING SYSTEM INFORMATION
# ============================================================
print("\n1. OPERATING SYSTEM INFORMATION")
# OS name
print(f" OS name: {os.name}")
# System information (Windows, Linux, etc.)
# Use platform module for more detailed info
import platform
print(f" System: {platform.system()}")
print(f" Version: {platform.version()}")
print(f" Machine: {platform.machine()}")
print(f" Processor: {platform.processor()}")
# ============================================================
# USER INFORMATION
# ============================================================
print("\n2. USER INFORMATION")
# Get current user (using environment variable)
username = os.environ.get("USER", os.environ.get("USERNAME", "Unknown"))
print(f" Username: {username}")
# Get home directory
home = os.path.expanduser("~")
print(f" Home directory: {home}")
# ============================================================
# SYSTEM RESOURCES
# ============================================================
print("\n3. SYSTEM RESOURCES")
# Number of CPU cores
cpu_count = os.cpu_count()
print(f" CPU cores: {cpu_count}")
# Process ID
pid = os.getpid()
print(f" Process ID: {pid}")
# Parent process ID
ppid = os.getppid() if hasattr(os, 'getppid') else "Not available"
print(f" Parent PID: {ppid}")
# ============================================================
# PROCESS INFORMATION
# ============================================================
print("\n4. PROCESS INFORMATION")
# Process environment variables
print(" Process environment variables are the same as environment variables")
# Process command line arguments
# import sys
# print(f" Command line: {sys.argv}")
# ============================================================
# SYSTEM COMMANDS
# ============================================================
print("\n5. SYSTEM COMMANDS")
# Execute a system command
# On Windows: dir, on Linux/Mac: ls
import subprocess
try:
# List files in current directory (cross-platform)
if os.name == 'nt':
result = subprocess.run(['dir'], shell=True, capture_output=True, text=True)
else:
result = subprocess.run(['ls', '-la'], capture_output=True, text=True)
print(" Directory listing:")
print(f" {result.stdout[:200]}")
except Exception as e:
print(f" Command failed: {e}")
System information key points:
- os.name — operating system name
- platform.system() — detailed OS name
- os.cpu_count() — number of CPU cores
- os.getpid() — current process ID
Quick Check: How do you get the number of CPU cores? (Answer: os.cpu_count())
Real-World Example
Building a File Organizer
# Real-World Example: File Organizer
import os
import shutil
from datetime import datetime
print("=" * 60)
print("FILE ORGANIZER")
print("=" * 60)
class FileOrganizer:
"""Organize files by extension and date"""
def __init__(self, directory):
self.directory = directory
self.extensions = {
'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
'documents': ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.md'],
'spreadsheets': ['.xls', '.xlsx', '.csv'],
'presentations': ['.ppt', '.pptx', '.key'],
'audio': ['.mp3', '.wav', '.aac', '.flac'],
'video': ['.mp4', '.avi', '.mov', '.wmv', '.flv'],
'archives': ['.zip', '.rar', '.tar', '.gz', '.7z'],
'code': ['.py', '.js', '.html', '.css', '.java', '.c', '.cpp']
}
def get_category(self, filename):
"""Get the category of a file based on its extension"""
_, ext = os.path.splitext(filename)
ext = ext.lower()
for category, exts in self.extensions.items():
if ext in exts:
return category
return 'others'
def organize(self):
"""Organize files in the directory"""
print(f"\n Organizing: {self.directory}")
# Get all files in the directory
files = [f for f in os.listdir(self.directory)
if os.path.isfile(os.path.join(self.directory, f))]
print(f" Found {len(files)} files")
# Count organized files
organized = 0
for filename in files:
category = self.get_category(filename)
# Skip the organizer script itself
if filename == os.path.basename(__file__):
continue
# Create category directory if it doesn't exist
category_dir = os.path.join(self.directory, category)
if not os.path.exists(category_dir):
os.makedirs(category_dir)
print(f" Created: {category_dir}")
# Move the file
src = os.path.join(self.directory, filename)
dest = os.path.join(category_dir, filename)
# If file already exists, add timestamp
if os.path.exists(dest):
name, ext = os.path.splitext(filename)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
new_name = f"{name}_{timestamp}{ext}"
dest = os.path.join(category_dir, new_name)
shutil.move(src, dest)
organized += 1
print(f" Organized {organized} files")
# Print summary
self.print_summary()
def print_summary(self):
"""Print a summary of the organization"""
print("\n Summary:")
for category in os.listdir(self.directory):
cat_dir = os.path.join(self.directory, category)
if os.path.isdir(cat_dir):
files = [f for f in os.listdir(cat_dir)
if os.path.isfile(os.path.join(cat_dir, f))]
if files:
print(f" {category}: {len(files)} files")
# ============================================================
# CREATE SAMPLE FILES
# ============================================================
def create_sample_files():
"""Create sample files for demonstration"""
os.makedirs("sample_files", exist_ok=True)
os.chdir("sample_files")
sample_files = [
"image1.jpg", "image2.png", "photo1.jpeg",
"document1.pdf", "document2.txt", "notes.docx",
"data1.csv", "data2.xlsx",
"presentation1.pptx", "slides.key",
"song1.mp3", "song2.wav",
"video1.mp4", "clip2.avi",
"archive1.zip", "file2.rar",
"script1.py", "code2.js", "style.css",
"unknown.xyz"
]
for filename in sample_files:
with open(filename, "w") as f:
f.write(f"Sample content for {filename}")
os.chdir("..")
print(" Created sample files in sample_files/")
# ============================================================
# DEMONSTRATION
# ============================================================
print("\n1. CREATING SAMPLE FILES")
create_sample_files()
print("\n2. ORGANIZING FILES")
organizer = FileOrganizer("sample_files")
organizer.organize()
print("\n3. CLEANING UP")
import shutil
shutil.rmtree("sample_files")
print(" Cleaned up sample_files/")
print("\n" + "=" * 60)
print("KEY TAKEAWAYS:")
print("=" * 60)
print("""
- OS module gives you control over files and directories
- Organize files by type automatically
- Move files to appropriate folders
- Handle duplicate files gracefully
- Cross-platform code works on all OS
""")
Real-world example key points:
- File organizer — automatically sorts files by type
- Categories — images, documents, audio, video
- os.path.join() — build paths safely
- shutil.move() — move files
- os.listdir() — find files in directory
Quick Check: How would you move a file from one folder to another? (Answer: Use shutil.move(src, dest))
Best Practices
Using OS Module Effectively
# Best Practices for OS Module
import os
import shutil
print("=" * 60)
print("BEST PRACTICES FOR OS MODULE")
print("=" * 60)
# ============================================================
# 1. USE os.path.join FOR PATHS
# ============================================================
print("\n1. USE os.path.join FOR PATHS")
# Good - works on all OS
path = os.path.join("folder", "subfolder", "file.txt")
print(f" Good path: {path}")
# Bad - manual path building (hardcoded slashes)
# path = "folder/subfolder/file.txt" # Windows uses backslash!
# ============================================================
# 2. USE exists BEFORE ACCESSING FILES
# ============================================================
print("\n2. USE exists BEFORE ACCESSING FILES")
# Good - check first
filename = "test.txt"
if os.path.exists(filename):
with open(filename, "r") as f:
content = f.read()
print(f" File exists and was read")
else:
print(f" File does not exist")
# Bad - no check (will crash if file doesn't exist)
# with open("missing.txt", "r") as f:
# content = f.read()
# ============================================================
# 3. USE shutil FOR FILE OPERATIONS
# ============================================================
print("\n3. USE shutil FOR FILE OPERATIONS")
# Good - use shutil for copy, move
shutil.copy("test.txt", "copy.txt") if os.path.exists("test.txt") else None
print(" Used shutil.copy")
# Bad - using os with open and read/write for copy (more code)
# with open("source.txt", "r") as f:
# content = f.read()
# with open("dest.txt", "w") as f:
# f.write(content)
# ============================================================
# 4. USE try/except FOR FILE OPERATIONS
# ============================================================
print("\n4. USE try/except FOR FILE OPERATIONS")
# Good - handle errors
try:
os.remove("missing.txt")
except FileNotFoundError:
print(" File not found - handled gracefully")
except PermissionError:
print(" Permission denied")
# ============================================================
# 5. USE PATHLIB FOR MODERN PATH OPERATIONS
# ============================================================
print("\n5. USE PATHLIB FOR MODERN PATH OPERATIONS")
from pathlib import Path
# Good - modern and clean
p = Path(".") / "folder" / "file.txt"
print(f" Pathlib path: {p}")
# Create with pathlib
p = Path("new_folder")
p.mkdir(exist_ok=True)
print(" Created with pathlib")
# Clean up
p.rmdir()
# ============================================================
# 6. SUMMARY
# ============================================================
print("\n" + "=" * 60)
print("BEST PRACTICES SUMMARY")
print("=" * 60)
print("""
- Use os.path.join for cross-platform paths
- Check exists before accessing files
- Use shutil for copy and move operations
- Use try/except for error handling
- Consider pathlib for modern path handling
- Always handle permissions and errors
""")
Best practices summary:
- os.path.join — for cross-platform paths
- Check exists — before accessing files
- Use shutil — for copy and move
- Use try/except — for error handling
- Consider pathlib — for modern path handling
Quick Check: Why should you use os.path.join instead of manual path building? (Answer: It's cross-platform and handles different path separators correctly)
Try It Yourself
Experiment with the OS module in the editor below.
OS MODULE - PRACTICE
==================================================
1. WORKING DIRECTORY
Current directory: /home/user
Files in directory: ['file1.py', 'file2.py', 'folder']
2. CREATE DIRECTORIES
Created: practice_dir
Created: practice_dir/sub/dir
3. CREATE FILE
Created: practice_dir/file.txt
File exists: True
4. PATH OPERATIONS
Joined path: practice_dir/sub/file.txt
Directory: practice_dir/sub
Filename: file.txt
5. CLEAN UP
Removed: practice_dir/file.txt
Removed: practice_dir
You've Got It!
You now understand the OS module in Python. You know how to work with files, directories, paths, environment variables, and system information.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the OS module in Python?
What's the difference between os.remove() and os.rmdir()?
How do I make my OS code work on Windows and Linux?
What's the difference between os and shutil?
Should I use os or pathlib?
How do I run a system command from Python?
subprocess.run(['ls', '-la']).
Where to Go From Here
Now that you understand the OS module, check out these related topics:
Sys Module
Learn about system-specific parameters and functions.
Learn More →JSON Module
Learn about working with JSON data.
Learn More →Datetime Module
Learn about working with dates and times with files.
Learn More →