Course Progress42%
🍎 Python Basics Topic 42 / 100
⏳ 7 min read

The os Module

Navigate folders, manage files, build cross-platform paths, and read environment variables — Python talks to the operating system through os.

"The os module is your Python script’s connection to the file system. Everything you do in a file manager, you can automate with os."

— ShurAI

Current Directory & Listing Files

python
import os

# Where is the script running?
print(os.getcwd())
# /home/riya/projects

# List everything in the current folder
print(os.listdir())
# [’main.py’, ’data’, ’README.md’]

# List a specific folder
print(os.listdir("/home/riya"))

# Change the working directory
os.chdir("/home/riya/projects")

Creating, Renaming, Deleting

python
# Create one folder
os.mkdir("reports")

# Create nested folders in one call
os.makedirs("data/2026/january", exist_ok=True)
# exist_ok=True: no error if the folder already exists

# Rename a file or folder
os.rename("old_report.txt", "new_report.txt")

# Delete a file
os.remove("temp.txt")

# Remove an empty folder
os.rmdir("old_reports")

os.path — Building and Checking Paths

os.path handles the difference between Windows (\) and Linux/Mac (/) automatically. Always use it instead of hard-coding slashes:

python
import os

# Build a cross-platform path
path = os.path.join("data", "2026", "report.csv")
print(path)         # data/2026/report.csv  (Linux/Mac)
                     # data\2026\report.csv (Windows)

# Does this path exist?
print(os.path.exists(path))    # True or False

# Is it a file? A folder?
print(os.path.isfile("main.py"))   # True
print(os.path.isdir("data"))       # True

# Extract parts of a path
full = "/home/riya/data/report.csv"
print(os.path.basename(full))   # report.csv
print(os.path.dirname(full))    # /home/riya/data
print(os.path.getsize("main.py")) # file size in bytes

Environment Variables

python
# Safe read — returns default if not set
home = os.environ.get("HOME", "unknown")
print(home)       # /home/riya

# Set a variable for this session
os.environ["APP_MODE"] = "development"
print(os.environ.get("APP_MODE"))  # development

Real Example — Python File Scanner

python
import os

def scan_py_files(folder):
    """Print all .py files and their sizes in a folder."""
    if not os.path.isdir(folder):
        print(f"Not found: {folder}")
        return
    print(f"Python files in ’{folder}’:")
    for item in sorted(os.listdir(folder)):
        full_path = os.path.join(folder, item)
        if os.path.isfile(full_path) and item.endswith(".py"):
            size = os.path.getsize(full_path)
            print(f"  {item:25} {size:6} bytes")

scan_py_files(".")

"Always use os.path.join() to build paths — never hard-code slashes. It is the one habit that makes your code work on every OS without changes."

— ShurAI

🧠 Quiz — Q1

What does os.getcwd() return?

🧠 Quiz — Q2

Why use os.path.join('data', 'file.csv') instead of 'data/file.csv'?

🧠 Quiz — Q3

What does os.makedirs('a/b/c', exist_ok=True) do?

🧠 Quiz — Q4

Which is the safest way to read an environment variable that might not exist?