Python os Module

Operating System

Python’s standard library is packed with tools that make programming easier, and one of the most useful is the os module. If you’re new to Python, the os module is your gateway to interacting with the operating system, whether you’re using Windows, macOS, or Linux. It lets you manage files, directories, and paths, and even perform system-level tasks like running commands. In this guide, we’ll explore the os module in depth with beginner-friendly explanations and plenty of examples. By the end, you’ll be able to use os to automate file operations, navigate directories, and make your programs more powerful. Let’s dive in!

This article is designed for beginners, so we’ll keep things simple, use clear examples, and include a practical exercise to solidify your learning. The current date and time, for reference, is September 18, 2025, at 08:19 PM +07.


What is the os Module?

The os module provides functions to interact with the operating system in a way that works across different platforms (Windows, macOS, Linux). It’s like a toolbox for tasks like:

  • Creating, renaming, or deleting files and folders.

  • Navigating directories.

  • Building and manipulating file paths.

  • Checking system information or running commands.

Think of os as a bridge between your Python code and your computer’s file system or operating system.


Key Features of the os Module

Let’s explore the main things you can do with os, organized by common tasks. We’ll include examples for each to make things clear.

1. Working with Directories

The os module lets you manage directories (folders) by creating, deleting, or navigating them.

Example 1: Creating and Navigating Directories

Here’s how to create a folder, change directories, and list contents:

import os

# Get the current working directory
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")

# Create a new directory
try:
    os.mkdir("my_folder")
    print("Created 'my_folder'")
except FileExistsError:
    print("'my_folder' already exists")

# Change to the new directory
os.chdir("my_folder")
print(f"Changed to: {os.getcwd()}")

# Go back to the parent directory
os.chdir("..")
print(f"Back to: {os.getcwd()}")

# List files and directories
files = os.listdir(".")
print(f"Files in current directory: {files}")

What’s happening?

  • os.getcwd() returns the current working directory as a string (e.g., /home/user/project on Linux).

  • os.mkdir(“my_folder”) creates a folder named my_folder. We use a try-except to handle cases where the folder already exists.

  • os.chdir(“my_folder”) changes the current directory to my_folder.

  • os.chdir(“..”) moves up one directory level.

  • os.listdir(“.”) lists all files and folders in the current directory (. means current directory).

Output (example):

Current directory: /home/user/project
Created 'my_folder'
Changed to: /home/user/project/my_folder
Back to: /home/user/project
Files in current directory: ['my_folder']

Example 2: Creating Nested Directories

If you need to create a directory with subdirectories (e.g., data/backup), use os.makedirs():

import os

# Create nested directories
try:
    os.makedirs("data/backup", exist_ok=True)
    print("Created 'data/backup'")
except FileExistsError:
    print("'data/backup' already exists")

# List contents to verify
print(os.listdir("data"))  # Output: ['backup']

What’s happening?

  • os.makedirs(“data/backup”, exist_ok=True) creates the data directory and its backup subdirectory. The exist_ok=True prevents errors if the directories already exist.

  • This is safer than os.mkdir(), which fails if parent directories don’t exist.

2. Working with File Paths

File paths differ across operating systems (e.g., Windows uses \, Linux/macOS use /). The os.path submodule ensures your code works everywhere.

Example 3: Building and Checking Paths

import os

# Join paths in a platform-independent way
path = os.path.join("my_folder", "test.txt")
print(f"Path: {path}")

# Check if a path exists
if os.path.exists(path):
    print(f"{path} exists")
else:
    print(f"{path} does not exist")

# Get the absolute path
absolute_path = os.path.abspath("test.txt")
print(f"Absolute path: {absolute_path}")

# Check if it's a file or directory
print(f"Is test.txt a file? {os.path.isfile('test.txt')}")
print(f"Is my_folder a directory? {os.path.isdir('my_folder')}")

What’s happening?

  • os.path.join(“my_folder”, “test.txt”) creates a path like my_folder/test.txt (Linux) or my_folder\test.txt (Windows).

  • os.path.exists(path) checks if the file or directory exists.

  • os.path.abspath(“test.txt”) returns the full path (e.g., /home/user/project/test.txt).

  • os.path.isfile() and os.path.isdir() check whether a path is a file or directory.

Output (example):

Path: my_folder/test.txt
my_folder/test.txt does not exist
Absolute path: /home/user/project/test.txt
Is test.txt a file? False
Is my_folder a directory? True

Example 4: Splitting Paths

You can split a path into components:

import os

path = os.path.join("data", "backup", "file.txt")
dirname = os.path.dirname(path)
basename = os.path.basename(path)
print(f"Directory: {dirname}")
print(f"Filename: {basename}")

# Split file extension
name, ext = os.path.splitext("file.txt")
print(f"Name: {name}, Extension: {ext}")

Output:

Directory: data/backup
Filename: file.txt
Name: file, Extension: .txt
  • os.path.dirname() gets the directory part (data/backup).

  • os.path.basename() gets the file part (file.txt).

  • os.path.splitext() splits the filename and extension.

3. Managing Files

The os module can create, rename, or delete files (though file content is handled with open()).

Example 5: Creating, Renaming, and Deleting Files

import os

# Create a file
with open("example.txt", "w") as f:
    f.write("Hello, Python!")
print("Created 'example.txt'")

# Check file size
size = os.path.getsize("example.txt")
print(f"File size: {size} bytes")

# Rename the file
os.rename("example.txt", "renamed.txt")
print("Renamed to 'renamed.txt'")

# Delete the file
os.remove("renamed.txt")
print("File deleted")

Output:

Created 'example.txt'
File size: 13 bytes
Renamed to 'renamed.txt'
File deleted
  • os.path.getsize() returns the file size in bytes.

  • os.rename() changes the file name.

  • os.remove() deletes the file.

4. System Information and Commands

The os module provides system details and can run commands (though subprocess is preferred for complex commands).

Example 6: System Information

import os

# Get operating system name
print(f"OS name: {os.name}")  # 'posix' (Linux/macOS) or 'nt' (Windows)

# Get environment variables
home_dir = os.getenv("HOME")  # or "HOMEPATH" on Windows
print(f"Home directory: {home_dir}")

# Get user ID (Linux/macOS)
if os.name == "posix":
    print(f"User ID: {os.getuid()}")

Output (example on Linux):

OS name: posix
Home directory: /home/user
User ID: 1000
  • os.name returns ‘posix’ for Unix-like systems or ‘nt’ for Windows.

  • os.getenv() retrieves environment variables like HOME.

  • os.getuid() gets the user ID (Unix-specific).

Example 7: Running a System Command

Use os.system() for simple commands (though subprocess is safer):

import os

# List directory contents (like 'ls' or 'dir')
os.system("dir" if os.name == "nt" else "ls")

This runs ls (Linux/macOS) or dir (Windows) to list directory contents.

Practical Use Cases

Here are some real-world scenarios where os shines:

  • File organization: Rename or move files based on their names or extensions.

  • Automation: Create folders for backups or project data.

  • Cross-platform scripts: Write code that works on any operating system.

  • System monitoring: Check file sizes or directory contents.

Practice Exercise: File Organizer

Let’s build a script that organizes files by their extension (e.g., move all .txt files to a text folder).

Save this as organize_files.py:

import os

def organize_files(directory: str) -> None:
    """Organize files in directory by their extension."""
    # Create directory if it doesn't exist
    os.makedirs(directory, exist_ok=True)
    os.chdir(directory)
    
    # Dictionary to map extensions to folders
    folders = {
        ".txt": "text",
        ".jpg": "images",
        ".png": "images"
    }
    
    # Create folders for each extension
    for folder in set(folders.values()):
        os.makedirs(folder, exist_ok=True)
    
    # Organize files
    for filename in os.listdir("."):
        if os.path.isfile(filename):
            name, ext = os.path.splitext(filename)
            if ext in folders:
                destination = os.path.join(folders[ext], filename)
                os.rename(filename, destination)
                print(f"Moved {filename} to {folders[ext]}")
            else:
                print(f"Skipped {filename}: unknown extension")

# Create some test files
with open("note1.txt", "w") as f:
    f.write("Test note")
with open("photo.jpg", "w") as f:
    f.write("Test image")

# Run organizer
organize_files(".")

Output (example):

Moved note1.txt to text
Moved photo.jpg to images

What’s happening?

  • Creates folders for different file extensions.

  • Moves files to the appropriate folder based on their extension.

  • Skips files with unknown extensions.

  • Uses os.makedirs(), os.path.splitext(), and os.rename().

Try extending the script:

  • Add more extensions (e.g., .pdf to a documents folder).

  • Print the size of each moved file using os.path.getsize().

  • Skip files smaller than a certain size.

Tips for Beginners

  • Error handling: Always use try-except with os.mkdir() or os.remove() to handle cases like existing files or permission errors.

  • Use os.path: It makes your code work on any operating system.

  • Avoid os.system() for complex commands: Use the subprocess module instead for safety.

Conclusion

The os module is a must-know tool for Python programmers. It lets you manage files and directories, work with paths, and interact with the operating system in a portable way. Whether you’re automating file organization, checking system details, or building cross-platform scripts, os has you covered. Start with simple tasks like creating folders or listing files, then try the practice exercise to build your own file organizer. With practice, you’ll find os to be an indispensable part of your Python toolkit!

Leave a Reply

Your email address will not be published. Required fields are marked *