Python os Module Cheatsheet
The os module provides a portable way of using operating system dependent functionality like file management and directory navigation.
| | |
|---|
| Function | Description | Example |
os.getcwd() | Returns the Current Working Directory | os.getcwd() |
os.chdir(path) | Change the current working directory | os.chdir("/home/user") |
os.listdir(path) | List files and folders in a directory | os.listdir(".") |
os.walk(path) | Yields a 3-tuple (dirpath, dirnames, filenames) | for r, d, f in os.walk("."): |
2. File & Directory Operations
| | |
|---|
| Function | Description | Example |
os.mkdir(dir) | Create a single directory | os.mkdir("new_folder") |
os.makedirs(path) | Create nested directories (recursive) | os.makedirs("a/b/c") |
os.remove(file) | Delete a file | os.remove("data.txt") |
os.rmdir(dir) | Remove an empty directory | os.rmdir("old_folder") |
os.rename(src, dst) | Rename or move a file/directory | os.rename("old.txt", "new.txt") |
3. Path Manipulations (os.path)
| | |
|---|
| Function | Description | Example |
os.path.join(p1, p2) | Joins path components intelligently | os.path.join("dir", "file.py") |
os.path.abspath(path) | Returns the absolute version of a path | os.path.abspath("test.py") |
os.path.basename(path) | Returns the file name part of a path | os.path.basename("/a/b.txt") → "b.txt" |
os.path.dirname(path) | Returns the directory part of a path | os.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 extension | os.path.splitext("a.mp4") → ('a', '.mp4') |
4. Path Checking (Booleans)
| | |
|---|
| Function | Description | Example |
os.path.exists(path) | Checks if a path exists | os.path.exists("config.json") |
os.path.isfile(path) | Returns True if path is a file | os.path.isfile("main.py") |
os.path.isdir(path) | Returns True if path is a directory | os.path.isdir("src") |
os.path.isabs(path) | Returns True if path is absolute | os.path.isabs("/etc/hosts") |
| | |
|---|
| Function | Description | Example |
os.environ | A mapping object representing environment variables | os.environ.get("USER") |
os.name | Returns ‘posix’, ‘nt’, or ‘java’ | os.name |
os.getlogin() | Returns the name of the logged-in user | os.getlogin() |
os.cpu_count() | Returns the number of CPUs in the system | os.cpu_count() |
os.system(cmd) | Executes a command in a subshell | os.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")]