Ten short, practical Python snippets for everyday data work using only the standard library: reading and writing CSV and JSON, counting, grouping, dates, file paths, deduplicating, and simple command-line tools, with notes on pitfalls.
You don't need big libraries for many everyday data jobs. These snippets use only Python's standard library, so they work anywhere Python 3 is installed. Each includes a note on what can go wrong.
1. Read a CSV into dictionaries
import csv
with open("sales.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
print(rows[0]["region"])
Watch out: every value is a string. Convert numbers with float() or int(). Always pass newline="" when opening CSV files.
2. Write a CSV
import csv
with open("out.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["name", "total"])
w.writeheader()
w.writerows([{"name": "A", "total": 3}, {"name": "B", "total": 5}])
If the file will be opened in Excel and contains accented characters, encoding="utf-8-sig" helps Excel detect the encoding.
3. Load and save JSON
import json
from pathlib import Path
data = json.loads(Path("config.json").read_text(encoding="utf-8"))
Path("copy.json").write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
ensure_ascii=False keeps characters such as £ readable.
4. Count things
from collections import Counter
regions = Counter(r["region"] for r in rows)
print(regions.most_common(3))
5. Group and total
from collections import defaultdict
totals = defaultdict(float)
for r in rows:
totals[r["region"]] += float(r["amount"])
For money, consider decimal.Decimal to avoid floating-point rounding surprises, such as 0.1 + 0.2 not equalling exactly 0.3.
6. Parse and format UK dates
from datetime import datetime
d = datetime.strptime("20/10/2026", "%d/%m/%Y")
print(d.strftime("%-d %B %Y")) # 20 October 2026 (Linux/macOS)
Watch out: %-d isn't supported on Windows; use %#d there, or str(d.day). Use ISO format (d.date().isoformat()) when storing dates.
7. Work with file paths
from pathlib import Path
for p in Path("reports").glob("*.csv"):
print(p.name, p.stat().st_size)
pathlib handles Windows and Unix separators for you. Use rglob to search subfolders.
8. Remove duplicates but keep order
emails = ["[email protected]", "[email protected]", "[email protected]"]
unique = list(dict.fromkeys(e.strip().lower() for e in emails))
Normalise first (trim and lowercase), or "[email protected]" and "[email protected]" count as different.
9. Sort by a field
top = sorted(rows, key=lambda r: float(r["amount"]), reverse=True)[:10]
Use operator.itemgetter for simple keys, and a tuple to sort by several fields.
10. A tiny command-line tool
import argparse, csv
ap = argparse.ArgumentParser(description="Sum a CSV column")
ap.add_argument("file"); ap.add_argument("column")
a = ap.parse_args()
with open(a.file, newline="", encoding="utf-8") as f:
print(sum(float(r[a.column]) for r in csv.DictReader(f)))
Run it with python sumcol.py sales.csv amount. argparse gives you --help for free.
Bonus: process a big file line by line
errors = 0
with open("server.log", encoding="utf-8", errors="replace") as f:
for line in f:
if " ERROR " in line:
errors += 1
print(errors)
Iterating over the file object reads one line at a time, so memory use stays low even for multi-gigabyte logs. errors="replace" stops one bad byte from crashing the whole run.
Bonus: fetch JSON from a web API
import json, urllib.request
req = urllib.request.Request("https://api.example.com/items", headers={"User-Agent": "my-script"})
with urllib.request.urlopen(req, timeout=10) as r:
items = json.load(r)
Always set a timeout so a slow server can't hang your script, and respect the API's rate limits and terms. Never paste API keys into code you share; read them from an environment variable with os.environ.
When to reach for a library?
For large datasets, joins, pivot tables or charts, pandas or Polars will be quicker to write and run. For spreadsheets, openpyxl reads and writes Excel files. Install libraries in a virtual environment rather than system-wide.
Frequently asked questions
Why does my CSV have blank lines on Windows?
You probably opened the file without newline="".
Which Python version do I need?
These snippets work on any supported Python 3 version.
Sources and further reading
- Python docs: csv
- Python docs: collections
- Python docs: datetime format codes
- Python docs: pathlib
- Python docs: argparse tutorial
Facts checked on 20 October 2026. Spotted an error? Tell us and we will correct it.
