Compare CSV versions by an exact key with Python
Writes added, removed and changed records to comparison.json without modifying either input. Change id only when you have another complete unique key.
Before you start
- Python 3.10 or later. Run in a working folder with a backup of your source; output files may be replaced unless opened in exclusive mode.
- Place original.csv and updated.csv in that folder. Examples use UTF-8, a comma delimiter and a header row. Column-specific recipes use id,label,amount,status,note; adapt names to your file.
python3 - <<'PY'
import csv
import json
def load(path):
with open(path, encoding="utf-8-sig", newline="") as source:
table = list(csv.reader(source, strict=True))
headers, rows = table[0], table[1:]
if len(set(headers)) != len(headers) or any(len(row) != len(headers) for row in rows):
raise ValueError("Expected unique headers and rectangular records")
column = headers.index("id")
keys = [row[column] for row in rows]
if any(not key for key in keys) or len(set(keys)) != len(keys):
raise ValueError("id must be unique and nonblank")
return headers, dict(zip(keys, rows))
headers, original = load("original.csv")
updated_headers, updated = load("updated.csv")
if headers != updated_headers:
raise ValueError("Header names and order must match")
report = {
"added": [row for key, row in updated.items() if key not in original],
"removed": [row for key, row in original.items() if key not in updated],
"changed": [{"id": key, "before": original[key], "after": row}
for key, row in updated.items() if key in original and original[key] != row],
"columns": headers,
}
with open("comparison.json", "w", encoding="utf-8") as target:
json.dump(report, target, ensure_ascii=False, indent=2)
print("Wrote comparison.json")
PYLimits and output
- CSV has no stored type schema. Python keeps fields as strings until an example explicitly converts a value. These recipes do not add spreadsheet formula protection; import sensitive-looking strings as text in spreadsheets.
- This recipe retains the parsed table in memory; use a streaming approach for files that do not fit.
Documentation: Python CSV reader and writer