Python os Module Cheatsheet

The os module provides a portable way of using operating system dependent functionality like file management and directory navigation.

1. Directory Navigation & Information

FunctionDescriptionExample
os.getcwd()Returns the Current Working Directoryos.getcwd()
os.chdir(path)Change the current working directoryos.chdir("/home/user")
os.listdir(path)List files and folders in a directoryos.listdir(".")
os.walk(path)Yields a 3-tuple (dirpath, dirnames, filenames)for r, d, f in os.walk("."):

2. File & Directory Operations

FunctionDescriptionExample
os.mkdir(dir)Create a single directoryos.mkdir("new_folder")
os.makedirs(path)Create nested directories (recursive)os.makedirs("a/b/c")
os.remove(file)Delete a fileos.remove("data.txt")
os.rmdir(dir)Remove an empty directoryos.rmdir("old_folder")
os.rename(src, dst)Rename or move a file/directoryos.rename("old.txt", "new.txt")

3. Path Manipulations (os.path)

FunctionDescriptionExample
os.path.join(p1, p2)Joins path components intelligentlyos.path.join("dir", "file.py")
os.path.abspath(path)Returns the absolute version of a pathos.path.abspath("test.py")
os.path.basename(path)Returns the file name part of a pathos.path.basename("/a/b.txt") "b.txt"
os.path.dirname(path)Returns the directory part of a pathos.path.dirname("/a/b.txt") "/a"
os.path.split(path)Returns (dirname, basename)os.path.split("/a/b.txt")
os.path.splitext(path)Splits the path from the file extensionos.path.splitext("a.mp4") ('a', '.mp4')

4. Path Checking (Booleans)

FunctionDescriptionExample
os.path.exists(path)Checks if a path existsos.path.exists("config.json")
os.path.isfile(path)Returns True if path is a fileos.path.isfile("main.py")
os.path.isdir(path)Returns True if path is a directoryos.path.isdir("src")
os.path.isabs(path)Returns True if path is absoluteos.path.isabs("/etc/hosts")

5. System Information & Environment

FunctionDescriptionExample
os.environA mapping object representing environment variablesos.environ.get("USER")
os.nameReturns ‘posix’, ‘nt’, or ‘java’os.name
os.getlogin()Returns the name of the logged-in useros.getlogin()
os.cpu_count()Returns the number of CPUs in the systemos.cpu_count()
os.system(cmd)Executes a command in a subshellos.system("ls -l")

6. Practical Snippets

Safe Path Joining

import os

folder = "data"
filename = "results.csv"
full_path = os.path.join(folder, filename)
# Result: 'data/results.csv' (Unix) or 'data\results.csv' (Windows)

Checking and Creating a Directory

if not os.path.exists("logs"):
    os.makedirs("logs")

Filtering Files by Extension

files = [f for f in os.listdir(".") if f.endswith(".py")]