Codectionary / Developer documentation / Python

os Module

The os module provides functions for interacting with the operating system - working with file paths, listing directory contents, creating and removing folders, and reading environment variables. Its os.path submodule (or the more modern pathlib alternative) handles cross-platform file path manipulation, so your code works correctly on Windows, macOS, and Linux without hardcoding path separators.

Syntax

import os

Examples

Working with Paths

Joining and inspecting file paths in a cross-platform way.

import os

path = os.path.join("data", "reports", "summary.csv")
print(path)  # data/reports/summary.csv (or data\\reports\\summary.csv on Windows)

print(os.path.exists(path))   # True or False
print(os.path.basename(path)) # summary.csv
print(os.path.dirname(path))  # data/reports

Listing Directory Contents

Getting a list of files and folders within a directory.

import os

files = os.listdir(".")  # current directory
print(files)

for name in os.listdir("."):
    if os.path.isfile(name):
        print(f"File: {name}")
    elif os.path.isdir(name):
        print(f"Directory: {name}")

Environment Variables

Reading environment variables, commonly used for configuration like API keys.

import os

api_key = os.environ.get("API_KEY", "default-key")
print(api_key)

# Setting an environment variable for the current process
os.environ["DEBUG"] = "true"

Creating and Removing Directories

Managing folders on the filesystem.

import os

os.makedirs("output/reports", exist_ok=True)  # creates nested dirs, no error if they exist
print(os.path.exists("output/reports"))  # True

os.rmdir("output/reports")  # removes an empty directory

Best practices

  • Use os.path.join() (or pathlib) instead of manually concatenating strings with "/" or "\\" for cross-platform compatibility
  • Use os.environ.get(key, default) rather than os.environ[key] when a variable might not be set, to avoid a KeyError
  • Use os.makedirs(path, exist_ok=True) instead of os.mkdir() when a path might have missing parent directories
  • Consider pathlib.Path for new code - it offers a more modern, object-oriented API that many developers find more readable than os.path

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading