Programming

20 Python Recipes for the Things You Keep Googling

Twenty short, copy-ready Python snippets for the work you do every week: files, dicts, text, dates and scripts, all using the standard library.

Ankit Singh
Software Engineer
·
6 min read
·
AI-assisted

AI tooling disclosure

Generative AI materially contributed to this article.

Human review confirmed by the author.

20 Python Recipes for the Things You Keep Googling

Nobody remembers the exact arguments to csv.DictWriter, and that's fine. Most everyday Python is made of small moves like that: read a file, count things, fix a date, run a command.

Here are 20 of them as micro-recipes. Each one is short, runs as written, and comes with one note about the thing that usually trips people up. Everything uses the standard library, so there's nothing to install.

Versions: every snippet was run on Python 3.12. The recipes that need a recent version say so.


Files and data

1. Read and write a text file

from pathlib import Path

path = Path("notes.txt")
path.write_text("hello\nworld\n", encoding="utf-8")

text = path.read_text(encoding="utf-8")
lines = text.splitlines()
print(lines)  # ['hello', 'world']

Heads up: always pass encoding. The default depends on the operating system, which is how scripts that work on your laptop break on a colleague's Windows machine. For huge files, loop over path.open() instead of reading everything at once.

2. Find files recursively

from pathlib import Path

for path in sorted(Path("src").rglob("*.py")):
    print(path.stem, path.suffix, path.stat().st_size)

rglob searches every subfolder. Use glob("*.py") to stay in one folder. Each Path also gives you .name, .stem, .suffix and .parent for free, so you never need to slice strings.

3. Read and write JSON

import json
from pathlib import Path

config = {"name": "demo", "retries": 3}
Path("config.json").write_text(json.dumps(config, indent=2), encoding="utf-8")

loaded = json.loads(Path("config.json").read_text(encoding="utf-8"))
print(loaded["retries"])  # 3

Heads up: dumps and loads work with strings; dump and load work with open files. If your data contains dates, pass default=str to dumps, or it raises a TypeError.

4. Read and write CSV as dictionaries

import csv

rows = [{"name": "Asha", "email": "[email protected]"}]

with open("users.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["name", "email"])
    writer.writeheader()
    writer.writerows(rows)

with open("users.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["email"])  # Asha [email protected]

Heads up: newline="" is required, or you get blank lines on Windows. Every value comes back as a string, so convert numbers yourself with int(row["age"]).


Scripts and the command line

5. Add command-line arguments

import argparse

parser = argparse.ArgumentParser(description="Resize images")
parser.add_argument("folder")
parser.add_argument("--width", type=int, default=800)
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()

print(args.folder, args.width, args.dry_run)

Run it as python resize.py photos --width 400 --dry-run. You get type conversion, defaults and a free --help page. A dash in the flag becomes an underscore in the code: --dry-run is args.dry_run.

6. Run a shell command and capture the output

import subprocess

result = subprocess.run(
    ["git", "status", "--short"],
    capture_output=True,
    text=True,
    check=True,
    timeout=30,
)
print(result.stdout)

Heads up: pass the command as a list, not one long string. Avoid shell=True whenever any part of the command comes from user input. check=True raises CalledProcessError on a non-zero exit code, so failures don't pass silently.


Lists and dicts

7. Count things

from collections import Counter

words = "the cat saw the dog and the cat ran".split()
counts = Counter(words)
print(counts.most_common(2))  # [('the', 3), ('cat', 2)]

A Counter behaves like a dict, and missing keys return 0 instead of raising an error.

8. Group things by a key

from collections import defaultdict
from pathlib import Path

by_ext = defaultdict(list)
for name in ["a.py", "b.txt", "c.py"]:
    by_ext[Path(name).suffix].append(name)

print(dict(by_ext))  # {'.py': ['a.py', 'c.py'], '.txt': ['b.txt']}

No more if key not in d: d[key] = []. Use defaultdict(int) when you want running totals instead of lists.

9. Merge dictionaries

defaults = {"timeout": 10, "retries": 3}
overrides = {"timeout": 30}

settings = defaults | overrides
print(settings)  # {'timeout': 30, 'retries': 3}

The right side wins on conflicts. Needs Python 3.9+. The merge is shallow, so nested dicts are replaced, not combined.

10. Remove duplicates but keep the order

items = ["b", "a", "b", "c", "a"]
unique = list(dict.fromkeys(items))
print(unique)  # ['b', 'a', 'c']

set(items) also removes duplicates, but it scrambles the order. Dicts keep insertion order, so this trick doesn't. Items must be hashable.

11. Flatten a list of lists

from itertools import chain

nested = [[1, 2], [3], [4, 5]]
flat = list(chain.from_iterable(nested))
print(flat)  # [1, 2, 3, 4, 5]

This flattens exactly one level, which is almost always what you want.

12. Split a list into chunks

from itertools import batched

for batch in batched(range(7), 3):
    print(batch)
# (0, 1, 2)
# (3, 4, 5)
# (6,)

Perfect for sending records to an API in groups of 100. Needs Python 3.12+, and each batch is a tuple. The last one can be shorter.

13. Sort by more than one field

people = [("Ben", 31), ("Asha", 25), ("Cara", 31)]

ranked = sorted(people, key=lambda p: (-p[1], p[0]))
print(ranked)  # [('Ben', 31), ('Cara', 31), ('Asha', 25)]

The key returns a tuple: oldest first (the minus sign flips the number), then name A to Z. This only works for numbers. For descending text, sort twice, since Python's sort is stable.

14. Pair two lists without silent data loss

names = ["Asha", "Ben", "Cara"]
scores = [90, 85]

for name, score in zip(names, scores, strict=True):
    print(name, score)
# Asha 90
# Ben 85
# ValueError: zip() argument 2 is shorter than argument 1

Plain zip quietly stops at the shortest list, so Cara would vanish without a warning. strict=True turns that into an error. Needs Python 3.10+.


Text

15. Pull fields out of a string with regex

import re

line = "2026-11-22 ERROR payment failed order=1042"
pattern = r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<level>[A-Z]+) .*order=(?P<order>\d+)"

match = re.search(pattern, line)
if match:
    print(match["date"], match["level"], match["order"])  # 2026-11-22 ERROR 1042

Heads up: use raw strings (r"...") for patterns, and always check for None before using the match. Named groups make the code readable six months later. Use re.findall when you want every match, not just the first.

16. Format numbers with f-strings

price = 1234567.891
x = 7

print(f"{price:,.2f}")   # 1,234,567.89
print(f"{0.256:.1%}")    # 25.6%
print(f"{42:05d}")       # 00042
print(f"{'name':<10}|")  # name      |
print(f"{x=}")           # x=7

The part after the colon is a format spec: , adds thousands separators, .2f is two decimals, % multiplies by 100, <10 pads to ten characters. The x= form prints the name and the value, which is great for quick debugging.


Dates and time

17. Parse, format and shift dates

from datetime import datetime, timedelta

dt = datetime.strptime("2026-11-22 14:30", "%Y-%m-%d %H:%M")

print(dt.strftime("%d %b %Y"))  # 22 Nov 2026
print(dt + timedelta(days=30))  # 2026-12-22 14:30:00

other = datetime.fromisoformat("2026-12-25T09:00:00")
print((other - dt).days)        # 32

strptime turns text into a date, strftime turns a date into text. For ISO-style strings, fromisoformat needs no format code at all. Subtracting two datetimes gives a timedelta.

18. Convert between time zones

from datetime import datetime
from zoneinfo import ZoneInfo

meeting = datetime(2026, 11, 22, 9, 0, tzinfo=ZoneInfo("America/New_York"))
print(meeting.astimezone(ZoneInfo("Asia/Kolkata")))  # 2026-11-22 19:30:00+05:30

Heads up: store and compare times in UTC, and convert only for display. Avoid datetime.utcnow(). It's deprecated since Python 3.12 and returns a naive datetime. Use datetime.now(ZoneInfo("UTC")) instead. On Windows you may need pip install tzdata.


Speed

19. Run slow I/O tasks in parallel

from concurrent.futures import ThreadPoolExecutor
from urllib.request import urlopen

def fetch_status(url):
    with urlopen(url, timeout=10) as response:
        return response.status

urls = ["https://example.com", "https://python.org"]

with ThreadPoolExecutor(max_workers=8) as pool:
    statuses = list(pool.map(fetch_status, urls))

print(statuses)  # [200, 200]

Threads shine when your code waits on the network or disk. Results come back in the same order as the input. If a call fails, the exception is raised when you read that result. For heavy number crunching, switch to ProcessPoolExecutor.

20. Cache a function's results

from functools import cache

@cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80))  # 23416728348467685

Add @cache to any function that is slow and gets called repeatedly with the same arguments. Arguments must be hashable. The cache grows forever, so use lru_cache(maxsize=1000) for long-running programs, and call fib.cache_clear() to reset it.


The cheat sheet

I need to...

Reach for

Read or write a file

Path.read_text() / Path.write_text()

Find files

Path.rglob()

Handle JSON

json.loads() / json.dumps()

Handle CSV

csv.DictReader / csv.DictWriter

Build a CLI

argparse

Run a command

subprocess.run(..., check=True)

Count things

Counter

Group things

defaultdict(list)

Merge dicts

the dict union operator

Dedupe in order

dict.fromkeys()

Flatten a list

chain.from_iterable()

Chunk a list

batched()

Sort by several fields

sorted(key=...) with a tuple

Pair lists safely

zip(strict=True)

Extract from text

re with named groups

Format numbers

f-string format specs

Parse dates

strptime() / fromisoformat()

Convert time zones

zoneinfo.ZoneInfo

Parallelize I/O

ThreadPoolExecutor

Cache results

functools.cache

Pick five you use most, paste them into a snippets file, and stop memorizing. For everything else, help() and the official docs are one keystroke away.

Comments(0)

Join the discussion by logging into your account.

No comments yet. Be the first to comment!

Ankit Singh
Ankit Singh

Software Engineer

Passionate developer sharing knowledge about modern web technologies and best practices.

Subscribe to Ankit Singh's Newsletter

Direct email dispatches when new stories are published. Zero algorithms.