Python Cheat Sheet
Conventions used everywhere
- Python counts columns from 0,
awkfrom 1. So awk$1=r[0], awk$7=r[6]. - Check your real column numbers first:
print(rows[0])orawk '{print $7}' access.log | head. line.split()splits on any whitespace and drops empty fields.line.split(" ")splits on exactly one space and keeps empty fields.- Lines from a file end in
\n. Userstrip("\n")beforesplit(sep)with an explicit separator.
1. Read a file and loop through it, accessing the split data
with open("access.log", encoding="utf-8", errors="replace") as f:
for line in f:
parts = line.split() # whitespace split, "\n" is removed automatically
if not parts: # blank line -> parts == [] -> parts[0] would raise IndexError
continue
ip = parts[0] # first column (awk $1)
path = parts[6] if len(parts) > 6 else "" # 7th column (awk $7), safe against short lines
Explicit separator (CSV-like, ;, |, …):
with open("data.txt", encoding="utf-8") as f:
for line in f:
parts = line.rstrip("\n").split(";") # rstrip first, otherwise the last field keeps "\n"
first, second = parts[0], parts[1]
Split only at the first N separators (useful when the last field contains the separator):
key, rest = "name=anna=muster".split("=", 1) # ['name', 'anna=muster']
Distinct error messages for read errors (single except Exception is a typical point-loss):
import sys
path = sys.argv[1] if len(sys.argv) > 1 else None
if path is None:
sys.exit("Usage: python script.py <logfile>")
try:
with open(path, encoding="utf-8", errors="replace") as f:
lines = f.readlines()
except FileNotFoundError as e:
sys.exit(f"File not found: {e}") # f-string / str(e): "text" + e raises TypeError
except IsADirectoryError as e:
sys.exit(f"Path is a directory: {e}")
except PermissionError as e:
sys.exit(f"No permission: {e}")
except OSError as e:
sys.exit(f"Read error: {e}")
2. Save the data into a list of lists
def load(path, sep=None):
"""Return rows[row][col], both 0-based. sep=None -> split on whitespace."""
rows = []
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
parts = line.rstrip("\n").split(sep) if sep else line.split()
if parts: # skip blank lines
rows.append(parts)
return rows
rows = load("access.log")
print(rows[0]) # always look at one row first
print(rows[0][6]) # row 0, column 6
Helpers on a list of lists:
def col(rows, i):
"""One column as a flat list."""
return [r[i] for r in rows if len(r) > i]
def apply_col(rows, i, func):
"""Run func on every value of column i, in place (lists are mutable, no return needed)."""
for r in rows:
r[i] = func(r[i])
ips = col(rows, 0)
3. Count things
from collections import Counter
counts = Counter(col(rows, 0)) # count how often each value appears
top = counts.most_common(10) # [(value, n), ...] sorted by n, descending
print(top)
Counter iteration order is insertion order. Only its print output shows entries sorted by count, so always use most_common() when order matters.
Manual version (no import):
plain = {}
for v in col(rows, 0):
plain[v] = plain.get(v, 0) + 1
ordered = sorted(plain.items(), key=lambda kv: kv[1], reverse=True) # by count, descending
Percentages:
total = sum(counts.values())
for k, n in counts.most_common(5):
print(f"{k}: {n} ({n / total * 100:.2f} %)")
4. Make visuals (matplotlib)
pip install matplotlib if needed.
Pie chart from a dict, percentages with two decimals:
import matplotlib
matplotlib.use("Agg") # no display needed (headless / SSH); remove if you want plt.show()
import matplotlib.pyplot as plt
data = dict(counts) # keys = labels, values = raw counts (no need to sum to 100)
fig, ax = plt.subplots(figsize=(7, 7))
ax.pie(data.values(), labels=data.keys(), autopct="%.2f%%") # %.2f = 2 decimals, %% = literal %
ax.set_title("Status codes")
fig.savefig("statuscode.png", dpi=300, bbox_inches="tight") # savefig BEFORE show()
plt.close(fig)
Bar chart (top N, with value labels):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
top = counts.most_common(10)
labels = [k for k, _ in top]
values = [n for _, n in top]
fig, ax = plt.subplots(figsize=(9, 5))
bars = ax.bar(labels, values)
ax.bar_label(bars) # needs matplotlib 3.4+
ax.set_ylabel("Requests")
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
fig.savefig("top_ips.png", dpi=300, bbox_inches="tight")
plt.close(fig)
Too many slices make a pie unreadable. Pie for few categories (status codes), bar for top-N lists (IPs).
5. Save into CSV, JSON or YAML (one entry per line, with \n)
CSV (list of lists)
import csv
header = ["value", "count"]
rows_out = [[k, n] for k, n in counts.most_common()]
with open("results.csv", "w", newline="", encoding="utf-8") as f: # newline="" avoids blank lines on Windows
w = csv.writer(f, delimiter=",") # delimiter=";" for Excel with Swiss/German locale
w.writerow(header)
w.writerows(rows_out)
Plain version without the csv module (breaks if a value contains the separator):
with open("results.csv", "w", encoding="utf-8") as f:
f.write("value,count\n")
for k, n in counts.most_common():
f.write(f"{k},{n}\n")
JSON, one key-value pair per line
json.dump(..., indent=2) puts nested structures on several lines, and without indent everything lands on one line. If a task says “one pair per line”, write it yourself:
import json
items = counts.most_common() # already sorted, descending
with open("results.json", "w", encoding="utf-8") as f:
f.write("{\n")
f.write(",\n".join(f" {json.dumps(str(k))}: {json.dumps(n)}" for k, n in items))
f.write("\n}\n")
Both {...} (object) and [...] (array) are valid JSON. If the task wording is open, note your choice in a comment.
Quick standard version:
import json
with open("results.json", "w", encoding="utf-8") as f:
json.dump(dict(counts.most_common()), f, indent=2)
JSON Lines (one object per line, each line valid on its own):
import json
with open("results.jsonl", "w", encoding="utf-8") as f:
for k, n in counts.most_common():
f.write(json.dumps({"value": k, "count": n}) + "\n")
YAML, one key per line
pip install pyyaml. sort_keys needs PyYAML 5.1+.
import yaml
data = dict(counts.most_common()) # insertion order = descending by count
with open("results.yml", "w", encoding="utf-8") as f:
for k, n in data.items():
yaml.safe_dump({k: n}, f, default_flow_style=False, sort_keys=False)
- One
safe_dumpper key, sosort_keys=Truewould do nothing. Sort withsorted()ormost_common()first and keepsort_keys=False. - Whole dict at once:
yaml.safe_dump(data, f, sort_keys=False). With realintkeys,sort_keys=Truesorts numerically. String keys like"10"sort as text ("10"before"2"). - Mixed
int/strkeys withsort_keys=TrueraiseTypeError.
No-dependency YAML for flat, simple data only (no quoting or escaping, so special characters can break it):
with open("results.yml", "w", encoding="utf-8") as f:
for k, n in counts.most_common():
f.write(f"{k}: {n}\n")
Write errors with a distinct message
try:
with open("out.txt", "w", encoding="utf-8") as f:
f.write("text\n")
except OSError as e:
print(f"Write error: {e}") # different text than the read error
6. HMAC pseudonymization
HMAC = hash that depends on a secret key: HMAC(K, m) = H((K xor opad) || H((K xor ipad) || m)). Same input and key give the same token, so records stay linkable. Another key gives a completely different token. Use hmac, not sha256(key + value).
import hashlib, hmac
KEY = b"change-me-use-a-long-random-key" # keep secret, long and random; never ship it with the data
def pseudo(value, prefix="x", n=8):
"""Same value + same KEY -> same token. lower() so 'Anna' and 'anna' match."""
digest = hmac.new(KEY, value.lower().encode(), hashlib.sha256).hexdigest()
return f"{prefix}-{digest[:n]}"
print(pseudo("192.0.2.10", "client")) # client-xxxxxxxx
Token length: 8 hex characters (32 bits) is fine for small logs. First collisions appear around 77,000 distinct values (birthday estimate). Use n=12 or n=16 for large files.
Pseudonymize a whole column (needs apply_col from section 2):
rows = load("access.log")
apply_col(rows, 0, lambda v: pseudo(v, "client")) # column 0 = IP
Pseudonymize a value inside a URL parameter (name=VALUE):
import re
def pseudo_param(text, name, prefix="x"):
"""Replace VALUE in name=VALUE. Skips values containing % (URL-encoded payloads, e.g. SQL injection)."""
def repl(m):
val = m.group(2)
return m.group(0) if "%" in val else f"{m.group(1)}{pseudo(val, prefix)}"
return re.sub(rf"({re.escape(name)}=)([^&\s]*)", repl, text)
print(pseudo_param("/login?login=anna.muster&x=1", "login", "user"))
apply_col(rows, 6, lambda v: pseudo_param(v, "login", "user")) # column 6 = path/URL in common log format
Redact a parameter completely:
import re
def redact_param(text, name):
return re.sub(rf"({re.escape(name)}=)[^&\s]*", r"\1REDACTED", text)
print(redact_param("/login?pass=secret&x=1", "pass"))
apply_col(rows, 6, lambda v: redact_param(v, "pass"))
redact_param also redacts a pass= value that holds an injection payload. Check your real pass= values first (grep -o 'pass=[^& ]*' access.log | sort | uniq -c | sort -nr | head) and add a % condition like in pseudo_param if payloads must stay visible.
Write the anonymized rows back:
def save(path, rows, sep=" "):
with open(path, "w", encoding="utf-8") as f:
for r in rows:
f.write(sep.join(r) + "\n")
save("access_anon.log", rows)
Regex pieces: [^&]* = any characters except & (stops at the next parameter). (...) = capture group, \1 / m.group(1) = its content.
SQLite column, work on a copy of the database:
import sqlite3
con = sqlite3.connect("copy.db")
for rid, v in con.execute("SELECT rowid, username FROM customers").fetchall():
con.execute("UPDATE customers SET username=? WHERE rowid=?", (pseudo(v, "user"), rid)) # ? placeholders, no .format()
con.commit()
con.close()
Pseudonymization vs. masking vs. anonymization:
| Reversible? | Records linkable? | Still personal data? | |
|---|---|---|---|
Masked (1973-XX-XX) | no, partly visible | partly | often yes |
| Pseudonymized (HMAC token) | with key or candidate list | yes | yes |
| Anonymized | no | no | no |
Checks with the shell after anonymizing:
awk '{print $1}' access_anon.log | sort | uniq -c | sort -nr | head # only tokens left?
grep -c 'pass=' access_anon.log; grep -c 'pass=REDACTED' access_anon.log # same number?
7. Small helpers
from datetime import datetime, date, timezone
# zero-padded fixed width: 100 -> "u0100"
uid = f"u{100:04d}"
# Unix timestamp -> dd.mm.yy HH:MM (local time of the machine). Higher timestamp = later date.
ts = 1700000000
print(datetime.fromtimestamp(ts).strftime("%d.%m.%y %H:%M"))
# UTC Timezone
ts = 1700000000 print(datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%d.%m.%y %H:%M"))
# age from birthdate, correct before/after the birthday
def age(born, today=None):
today = today or date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
print(age(date(1990, 6, 15)))
# part of an e-mail address
mail = "anna.muster@example.org"
user, domain = mail.split("@")
8. Full minimal pipeline (read, count, save, plot)
import sys
from collections import Counter
import yaml
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
path = sys.argv[1] if len(sys.argv) > 1 else "access.log"
try:
with open(path, encoding="utf-8", errors="replace") as f:
statuses = [p[8] for p in (l.split() for l in f) if len(p) > 8] # col 8 = status in common log format
except OSError as e:
sys.exit(f"Read error: {e}")
counts = Counter(statuses)
try:
with open("results.yml", "w", encoding="utf-8") as f:
for k, n in counts.most_common():
yaml.safe_dump({k: n}, f, sort_keys=False)
except OSError as e:
sys.exit(f"Write error: {e}")
fig, ax = plt.subplots(figsize=(6, 6))
ax.pie(counts.values(), labels=counts.keys(), autopct="%.2f%%")
fig.savefig("statuscode.png", dpi=300, bbox_inches="tight")
The status code is column 8 only for Apache common/combined log lines like IP - - [10/Oct/2026:13:55:36 +0200] "GET /path HTTP/1.1" 200 2326. Check with print(rows[0]) on your own file.