Skip to main content

Python Dev Config Cheatsheet

This cheatsheet covers common Python dev commands and snippets: venv, pip, data types, string methods, file I/O, module management, debugging, and more.

Updated: 2026-07-16·41 commands

Virtual Environment Management (py-env)

``bash # Create virtual environment python -m venv venv

# Activate venv (Linux/macOS) source venv/bin/activate

# Activate venv (Windows PowerShell) venv\Scripts\Activate.ps1

# Deactivate venv deactivate

# Export installed packages pip freeze > requirements.txt

# Install from requirements file pip install -r requirements.txt `

Package Management (py-env)

`bash # Install a package pip install requests

# Install a specific version pip install requests==2.31.0

# Upgrade a package pip install --upgrade requests

# Uninstall a package pip uninstall requests -y

# List installed packages pip list

# Show package details pip show requests

# Install to user directory (no sudo) pip install --user package

# Check outdated packages pip list --outdated `

Core Data Types (py-data)

`python # List operations lst = [1, 2, 3] lst.append(4) # [1, 2, 3, 4] lst.extend([5, 6]) # [1, 2, 3, 4, 5, 6] lst.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6] lst.remove(3) # [0, 1, 2, 4, 5, 6] popped = lst.pop() # popped=6, lst=[0, 1, 2, 4, 5]

# Dictionary operations d = {'a': 1, 'b': 2} d['c'] = 3 # {'a': 1, 'b': 2, 'c': 3} d.get('x', 0) # 0 (with default) d.setdefault('y', 4) # set default if key missing d.keys() # dict_keys(['a', 'b', 'c']) d.values() # dict_values([1, 2, 3]) d.items() # dict_items([('a',1), ('b',2), ('c',3)])

# Set operations s = {1, 2, 3} s.add(4) # {1, 2, 3, 4} s.discard(2) # {1, 3, 4} s1 = {1, 2, 3} s2 = {3, 4, 5} s1 & s2 # {3} intersection s1 | s2 # {1,2,3,4,5} union s1 - s2 # {1, 2} difference `

String Handling (py-string)

`python s = " hello world " s.strip() # "hello world" s.upper() # " HELLO WORLD " s.lower() # " hello world " s.split() # ['hello', 'world'] '-'.join(['a','b']) # "a-b" s.replace("world", "python") # " hello python " s.startswith("hel") # True s.find("world") # 8 s.count("l") # 3

# f-string formatting name = "Alice" age = 30 f"Name: {name}, Age: {age}" # "Name: Alice, Age: 30" f"{3.14159:.2f}" # "3.14" f"{1000:>10}" # " 1000" (right-aligned)

# String slicing text = "python" text[0:3] # "pyt" text[::-1] # "nohtyp" text[::2] # "pto" `

File I/O (py-file)

`python # Read file with open('file.txt', 'r', encoding='utf-8') as f: content = f.read() # read entirely lines = f.readlines() # read lines into list for line in f: # iterate line by line (memory-friendly) print(line.strip())

# Write file with open('file.txt', 'w', encoding='utf-8') as f: f.write('hello\n') f.writelines(['line1\n', 'line2\n'])

# Append to file with open('file.txt', 'a', encoding='utf-8') as f: f.write('append this\n')

# JSON file operations import json data = {'name': 'Alice', 'scores': [90, 85]} with open('data.json', 'w') as f: json.dump(data, f, indent=2) with open('data.json') as f: loaded = json.load(f)

# Path operations from pathlib import Path p = Path('/home/user/file.txt') p.name # "file.txt" p.stem # "file" p.suffix # ".txt" p.parent # "/home/user" p.exists() # True/False p.mkdir(parents=True, exist_ok=True) `

Modules & Argument Parsing (py-module)

`python # argparse for CLI arguments import argparse parser = argparse.ArgumentParser(description='My script') parser.add_argument('input', help='input file path') parser.add_argument('-o', '--output', default='out.txt', help='output file') parser.add_argument('-v', '--verbose', action='store_true', help='verbose mode') parser.add_argument('--count', type=int, default=1, help='number of times') args = parser.parse_args()

# sys module import sys sys.argv # CLI argument list sys.exit(0) # successful exit sys.exit(1) # error exit sys.path # module search path

# os module import os os.getcwd() # current working directory os.listdir('.') # list directory contents os.environ.get('HOME') # environment variable os.path.join('dir', 'file.txt') # path join `

Date & Random (py-module)

`python # datetime from datetime import datetime, timedelta now = datetime.now() now.strftime('%Y-%m-%d %H:%M:%S') # "2026-07-16 15:30:00" datetime.strptime('2026-07-16', '%Y-%m-%d') now + timedelta(days=7) # one week later now - timedelta(hours=3) # three hours ago

# random import random random.random() # [0.0, 1.0) random float random.randint(1, 10) # [1, 10] random integer random.choice(['a','b','c']) # random choice random.sample(range(100), 5) # non-repeating sample random.shuffle(list) # shuffle in-place `

Input/Output & Formatting (py-io)

`python # Input user_input = input("Enter name: ")

# Advanced print print("hello", "world", sep=", ") # hello, world print("loading", end="...\n") # custom end character print(f"value: {value:>10.2f}") # right-aligned, 2 decimals

# Exception handling try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except (ValueError, TypeError): print("Type or value error") else: print("No exception") finally: print("Always executed")

# Raise exceptions raise ValueError("invalid value") `

List Comprehensions & Debugging (py-debug)

``python # List comprehension squares = [x2 for x in range(10)] # [0, 1, 4, ..., 81] evens = [x for x in range(20) if x % 2 == 0] pairs = [(x, y) for x in [1,2] for y in [3,4]] # [(1,3),(1,4),(2,3),(2,4)]

# Dict comprehension square_dict = {x: x2 for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}

# Set comprehension unique_lens = {len(w) for w in ["hi", "hello", "hey"]} # {2, 3, 5}

# Generator expression gen = (x2 for x in range(1000000)) # lazy evaluation sum(x2 for x in range(10)) # 285

# Pretty print from pprint import pprint data = {'users': [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]} pprint(data, indent=2, depth=2)

# Breakpoint debugger (Python 3.7+) # breakpoint() # launches pdb debugger

# Timer decorator import time def timer(func): def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = time.perf_counter() - start print(f"{func.__name__} took: {elapsed:.4f}s") return result return wrapper

@timer def slow_function(): time.sleep(0.1) return "done"

Environment(8)

CommandLevel
python -m venv venv
Create a Python virtual environment
Basic
source venv/bin/activate
Activate virtual environment (Linux/macOS)
Basic
deactivate
Deactivate virtual environment
Basic
pip freeze > requirements.txt
Export installed packages to file
Basic
pip install -r requirements.txt
Install dependencies from requirements file
Basic
pip install requests==2.31.0
Install a specific package version
Basic
pip install --upgrade requests
Upgrade an installed package
Basic
pip list --outdated
Check outdated packages
Intermediate

Data Types(5)

CommandLevel
lst = [1, 2, 3]; lst.append(4)
Append element to list
Basic
d.get('x', 0)
Dict get with default value
Basic
d.setdefault('y', 4)
Set dict default if key is missing
Intermediate
s1 & s2
Set intersection operation
Basic
s1 - s2
Set difference operation
Basic

Strings(5)

CommandLevel
s.strip()
Strip leading/trailing whitespace
Basic
s.replace('world', 'python')
String replace
Basic
'-'.join(['a', 'b'])
Join string list with separator
Basic
f'Name: {name}, Age: {age}'
f-string formatted output
Basic
text[::-1]
Reverse string with step slicing
Intermediate

File I/O(5)

CommandLevel
open('file.txt', 'r', encoding='utf-8')
Open file in read mode (UTF-8)
Basic
json.dump(data, f, indent=2)
Serialize Python object to JSON file
Intermediate
json.load(f)
Load JSON file into Python object
Intermediate
Path('/tmp/file.txt').suffix
Get file extension
Basic
p.mkdir(parents=True, exist_ok=True)
Create directory recursively, no error if exists
Intermediate

Modules(8)

CommandLevel
argparse.ArgumentParser(description='My script')
Create CLI argument parser
Intermediate
sys.argv
Get CLI argument list
Basic
os.environ.get('HOME')
Get environment variable
Basic
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Get current time as formatted string
Basic
random.randint(1, 10)
Generate random integer in range
Basic
random.sample(range(100), 5)
Non-repeating random sample
Intermediate
@contextmanager
Custom context manager with contextmanager decorator
Expert
lru_cache
Function result caching with LRU strategy
Expert

I/O(5)

CommandLevel
input('Enter name: ')
Read a line from stdin
Basic
print('hello', 'world', sep=', ')
Print with custom separator
Basic
try ... except ... else ... finally
Complete exception handling structure
Intermediate
raise ValueError("invalid value")
Manually raise an exception
Intermediate
async with aiohttp.ClientSession() as session:
Async HTTP request (asyncio + aiohttp)
Expert

Debugging(5)

CommandLevel
[x**2 for x in range(10)]
List comprehension
Intermediate
{x: x**2 for x in range(5)}
Dict comprehension
Intermediate
(x**2 for x in range(1000000))
Generator expression (lazy evaluation)
Intermediate
breakpoint()
Launch pdb interactive debugger (Python 3.7+)
Intermediate
from pprint import pprint; pprint(data, indent=2)
Pretty-print nested data structures
Basic

FAQ

This cheatsheet is compiled from official tool documentation. Last updated: 2026-07-16.