PythonSnippets

Everyday Python 3 snippets (standard library only).

-- Read and write text files
from pathlib import Path
text = Path("notes.txt").read_text(encoding="utf-8")
Path("out.txt").write_text(text.upper(), encoding="utf-8")
for line in Path("notes.txt").open(encoding="utf-8"):
    print(line.rstrip("\n"))

-- CSV
import csv
with open("data.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):          # each row is a dict keyed by the header line
        print(row["name"], row["price"])
with open("out.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(["name", "price"])
    w.writerows([["apple", 1.25], ["pear", 0.90]])

-- JSON
import json
data = json.loads('{"a": 1, "b": [1, 2]}')
s = json.dumps(data, indent=2, sort_keys=True)
with open("data.json", encoding="utf-8") as f:
    cfg = json.load(f)

-- Dates and times
from datetime import datetime, date, timedelta, timezone
now = datetime.now(timezone.utc)
d = datetime.strptime("2024-03-15 14:30", "%Y-%m-%d %H:%M")
print(d.strftime("%A %d %B %Y"))           # Friday 15 March 2024
print(date(2024, 12, 25) - date.today())   # a timedelta
tomorrow = date.today() + timedelta(days=1)
iso = now.isoformat(timespec="seconds")
back = datetime.fromisoformat(iso)

-- Simple HTTP GET returning JSON
import json, urllib.request
req = urllib.request.Request("https://api.example.com/items", headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=10) as resp:
    items = json.load(resp)

-- Run a command and capture its output
import subprocess
r = subprocess.run(["ls", "-l"], capture_output=True, text=True, check=True)
print(r.stdout)

-- Count things
from collections import Counter
Counter("mississippi").most_common(2)     # [('i', 4), ('s', 4)]

-- Sort a list of dicts by a key
rows = sorted(rows, key=lambda r: (r["last"], r["first"]))

-- Command-line arguments
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("path")
ap.add_argument("-n", type=int, default=10)
args = ap.parse_args()

-- Format numbers
f"{1234567.891:,.2f}"    # '1,234,567.89'
f"{0.256:.1%}"           # '25.6%'
f"{42:08b}"              # '00101010'
Name (optional):

Or: /edit?page=PythonSnippets&text=your+text&name=YourName


Index | Recent changes | permalink | rev 574af8ace0f2