CSV Diff — Python source
Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""csv-diff — key-based row diff of two RFC-4180 CSVs. Python port (canonical TS:
src/lib/csv-diff.ts; Go twin: cli/csv-diff). Shared-parser semantics: quoted
cells (embedded commas, quotes, newlines), CR dropped, a trailing field without
a newline still completes its row, and blank single-cell rows dropped as
trailing noise. Strict per-side validation — empty CSV, duplicate columns,
ragged rows ("Left: row 2 has 3 cells, expected 4") — then a key-based diff
over the sorted key union: added/removed rows and changed rows whose differing
column names come out sorted. Never raises — errors travel in the result dict.
"""
def csv_to_rows(csv):
"""RFC 4180 parser mirroring the TS loop (lenient quotes, CR dropped)."""
rows, field, row, in_q = [], [], [], False
i, n = 0, len(csv)
while i < n:
ch = csv[i]
if in_q:
if ch == '"':
if i + 1 < n and csv[i + 1] == '"':
field.append('"')
i += 1
else:
in_q = False
else:
field.append(ch)
elif ch == '"':
in_q = True
elif ch == ",":
row.append("".join(field))
field = []
elif ch == "\n":
row.append("".join(field))
rows.append(row)
row, field = [], []
elif ch != "\r":
field.append(ch)
i += 1
if field or row:
row.append("".join(field))
rows.append(row)
return rows
def parse_csv(text):
"""Blank single-cell rows are trailing noise to a diff, not data."""
return [r for r in csv_to_rows(text) if not (len(r) == 1 and r[0] == "")]
def to_records(rows, label):
"""Strict per-side table → (header, records); ValueError on any structural
problem (empty CSV, duplicate column, ragged row) with the pinned strings."""
if not rows:
raise ValueError(f"{label}: empty CSV")
header = rows[0]
seen = set()
for name in header:
if name in seen:
raise ValueError(f'{label}: duplicate column "{name}"')
seen.add(name)
records = []
for r in range(1, len(rows)):
if len(rows[r]) != len(header):
raise ValueError(f"{label}: row {r + 1} has {len(rows[r])} cells, expected {len(header)}")
records.append(dict(zip(header, rows[r])))
return header, records
def csv_diff(left_raw, right_raw, key_column=None):
"""Diff two CSVs by key column (default: the first header column)."""
if not left_raw.strip() or not right_raw.strip():
return {"rows": [], "same": False, "error": "Both inputs are required"}
try:
lheader, lrecs = to_records(parse_csv(left_raw), "Left")
rheader, rrecs = to_records(parse_csv(right_raw), "Right")
key = key_column if key_column is not None else lheader[0]
if key not in lheader:
return {"rows": [], "same": False, "error": f'Left: no key column "{key}"'}
if key not in rheader:
return {"rows": [], "same": False, "error": f'Right: no key column "{key}"'}
if len(lheader) != len(rheader) or lheader != rheader:
return {"rows": [], "same": False,
"error": f"Headers differ: left [{', '.join(lheader)}] vs right [{', '.join(rheader)}]"}
def index(records, label):
by = {}
for rec in records:
if rec[key] in by:
raise ValueError(f'{label}: duplicate key "{rec[key]}"')
by[rec[key]] = rec
return by
left_by = index(lrecs, "Left")
right_by = index(rrecs, "Right")
out = []
for k in sorted(set(left_by) | set(right_by)):
l, r = left_by.get(k), right_by.get(k)
if l is None:
out.append({"key": k, "type": "added", "after": r})
elif r is None:
out.append({"key": k, "type": "removed", "before": l})
else:
columns = sorted(n for n in lheader if n != key and l[n] != r[n])
if columns:
out.append({"key": k, "type": "changed", "columns": columns, "before": l, "after": r})
return {"rows": out, "same": not out, "error": None}
except ValueError as e:
return {"rows": [], "same": False, "error": str(e)}
# Example:
# csv_diff("id,name\n1,Ada\n2,Bob", "id,name\n1,Ada\n2,Robert\n3,New")["rows"]
# → [{"key": "2", "type": "changed", "columns": ["name"], "before": {…}, "after": {…}},
# {"key": "3", "type": "added", "after": {"id": "3", "name": "New"}}]
Also available in 12 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →