You export a product list, someone edits it in a spreadsheet, and it comes back. What actually changed?
A line-by-line diff is the wrong tool for this. I took a 3-product CSV, changed nothing, and only let a spreadsheet do what spreadsheets do: sort the rows differently and save as UTF-8 with a BOM and Windows line endings. difflib.unified_diff reported 10 changed lines for a 5-line file — every line, because every line moved or got a and the first one got a BOM.
What you want instead is to match rows by a key column (sku, id, an email…) and compare cell by cell. That is what this script does.
The script
"""Compare two CSV exports by a key column and list added, removed and changed cells. Standard library only.
Usage: python csv_diff.py old.csv new.csv sku (exits with 1 if anything differs, 2 on an error)
"""
import csv
import io
import sys
class CsvError(Exception):
pass
def read_rows(path, key):
try:
raw = open(path, "rb").read()
except OSError as e:
raise CsvError(f"{path}: {e.strerror}")
if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
tried = ("utf-16",) # a UTF-16 file has a byte order mark
else:
tried = ("utf-8-sig", "cp932") # utf-8-sig also reads plain UTF-8 and drops a BOM
for enc in tried:
try:
text = raw.decode(enc)
break
except UnicodeDecodeError:
continue
else:
raise CsvError(f"{path}: not UTF-8, UTF-16 or Shift_JIS")
reader = csv.DictReader(io.StringIO(text, newline="")) # newline="" keeps line breaks inside quoted cells
if key not in (reader.fieldnames or []):
raise CsvError(f"{path}: no column named {key!r}")
rows, dupes = {}, []
for row in reader:
k = row[key].strip()
if k in rows:
dupes.append(k) # keep the first row, report the rest
continue
rows[k] = row
return rows, reader.fieldnames, enc, dupes
def diff(old_path, new_path, key):
old, old_cols, old_enc, old_dupes = read_rows(old_path, key)
new, new_cols, new_enc, new_dupes = read_rows(new_path, key)
print(f"old: {len(old)} rows ({old_enc}), new: {len(new)} rows ({new_enc})")
for k in old_dupes:
print(f"note: {key} {k} appears more than once in the old file (first row compared)")
for k in new_dupes:
print(f"note: {key} {k} appears more than once in the new file (first row compared)")
found = 0
for k in sorted(new.keys() - old.keys()):
print(f"added: {k}"); found += 1
for k in sorted(old.keys() - new.keys()):
print(f"removed: {k}"); found += 1
shared = [c for c in old_cols if c in new_cols and c != key]
for k in sorted(old.keys() & new.keys()):
for c in shared:
a, b = old[k][c].replace("\r\n", "\n"), new[k][c].replace("\r\n", "\n")
if a != b:
print(f"changed: {k} {c}: {a!r} -> {b!r}"); found += 1
for c in sorted(set(old_cols) ^ set(new_cols)):
print(f"column only in {'old' if c in old_cols else 'new'}: {c}"); found += 1
print("no differences" if not found else f"{found} difference{'s' if found > 1 else ''}")
return found
if __name__ == "__main__":
try:
sys.exit(1 if diff(*sys.argv[1:4]) else 0)
except CsvError as e:
print(f"error: {e}", file=sys.stderr)
sys.exit(2)
It exits with 0 when the files match, 1 when something differs and 2 on an error (missing file, missing key column, unreadable encoding), so it can sit in a script or a CI step.
What it handles, and how
Rows in a different order
Rows are stored in a dict by key, so order never matters. Only keys present on one side become added or removed.
BOM, CRLF and line breaks inside cells
-
utf-8-sigreads plain UTF-8 and silently drops the BOM that Excel writes. Without it, the first column header becomesskuand the key column "does not exist". - The
csvmodule documentation asks for files to be opened withnewline=""; the script decodes the bytes itself and gives the reader aStringIOwith the same setting, so no line endings are translated and a line break inside a quoted cell stays part of that cell instead of splitting the record. - Inside a cell,
is compared as, so a file saved on Windows does not differ from the same file saved elsewhere.
Other encodings
A file that starts with a UTF-16 byte order mark is read as UTF-16. Anything else is tried as UTF-8, then as cp932 (Shift_JIS as written by Japanese Windows and Excel), a common case for CSV files that come from Japanese shops and suppliers.
Duplicate keys
A second row with the same key is not compared; the script prints a note so you know the file is not clean.
Running it on files with planted problems
All outputs below are copied from real runs (Python 3.13.12, Windows 11).
| Files | Output | Exit |
|---|---|---|
| same 3 products, rows reordered, saved as UTF-8 with BOM and CRLF | no differences |
0 |
| price changed, stock changed, one product removed, one added, one line changed inside a multi-line description | 5 lines: added: C-300, removed: A-101, changed: A-100 price: '12.00' -> '13.50', `changed: A-100 description: 'Holds 350 ml. |
Dishwasher safe.' -> 'Holds 350 ml.
Microwave safe.', changed: B-200 stock: '12' -> '40' | 1 |old: 2 rows (cp932), new: 2 rows (utf-16)
| old file in Shift_JIS with Japanese product names, new file in UTF-16, one price changed | and changed: J-1 price: '1200' -> '1300' | 1 |A-101
| old file has twice | note: sku A-101 appears more than once in the old file (first row compared) | 0 |sku
| new file has no column | error: no_sku.csv: no column named 'sku'` | 2 |
For comparison, the line diff of the second case gave 8 changed lines and no hint of which product or which column changed.
What it does not do
- It does not normalize values:
12.0and12.00, orBlue mugandBlue mug(trailing space), are reported as changed. That is deliberate — for an import, those are different strings — but add.strip()or number parsing if you want looser matching. - Encoding detection is a short guess list, not a detector. A file in another legacy encoding (Latin-1, GBK…) will either fail or, rarely, decode wrongly; add it to the list if you know your source.
- Rows with an empty key cell all share the key
"": only the first is compared, the rest are reported as duplicates. - It does not read
.xlsx. Save as CSV first.
If the CSV is a Shopify product import, matching rows is only half of it: Shopify has its own column rules for the import itself (official CSV reference). We also made a free in-browser checker for those rules; nothing is uploaded.
This article was created with the help of AI (Claude Code). The script and every output above were run and checked before publishing.
Top comments (0)