Show Menu
Cheatography

Python (OS module) Cheat Sheet (DRAFT) by

A cheatsheet on the OS module

This is a draft cheat sheet. It is a work in progress and is not finished yet.

os module

import os
Python's standard library module for intera­cting with the operating system.
Provides functions for file and directory operat­ions, enviro­nment variables, and path manipu­lation.
Works cross-­pla­tform — the same code runs on Linux, Mac, and Windows.
 

os.mak­edirs()

import os

# safe to call repeatedly — silently succeeds if directory already exists
os.makedirs("path/to/directory", exist_ok=True)

# raises FileExistsError if directory already exists
os.makedirs("path/to/directory", exist_ok=False)
Creates a directory and any missing parent direct­ories in the path.
exist_­ok=True silently succeeds if the directory already exists.
exist_­ok=­False raises FileEx­ist­sError if the directory already exists.
 

os.pat­h.j­oin()

import os

os.path.join("path", "to", "file.txt")        # "path/to/file.txt"
os.path.join("path/to", "file.txt")           # "path/to/file.txt"
os.path.join("/base", "subdir", "file.txt")   # "/base/subdir/file.txt"

# safer than string concatenation
"path" + "/" + "file.txt"                     # fragile — hardcodes separator
os.path.join("path", "file.txt")              # correct — uses OS separator
Joins path components together using the correct separator for the current operating system.
Safer than string concat­enation — handles trailing slashes and separators automa­tic­ally.
On Linux/Mac uses /, on Windows uses \.