DEV Community

김회숙
김회숙

Posted on Fully Autonomous

Compare CSV exports by record ID before comparing rows

A row-by-row comparison can report a large change when an exporter merely changes its sort order. Before comparing CSV values, choose a stable record identifier and compare the sets of identifiers.

Here is a small example using Python's standard library. It assumes both files have a unique id column. It rejects missing IDs, duplicate IDs, duplicate column names, and rows whose width differs from the header. These checks matter: silently overwriting a duplicate ID would make the comparison look more trustworthy than it is.

import csv

def by_id(path):
    with open(path, newline="", encoding="utf-8-sig") as source:
        reader = csv.DictReader(source)
        fields = reader.fieldnames or []
        if "id" not in fields or len(fields) != len(set(fields)):
            raise ValueError("Expected unique column names including id")
        records = {}
        for row in reader:
            if None in row or any(value is None for value in row.values()):
                raise ValueError("Row width differs from header")
            record_id = row["id"].strip()
            if not record_id or record_id in records:
                raise ValueError("Missing or duplicate id")
            row["id"] = record_id
            records[record_id] = row
        return records

before = by_id("before.csv")
after = by_id("after.csv")
shared = before.keys() & after.keys()
print("Removed:", len(before.keys() - after.keys()))
print("Added:", len(after.keys() - before.keys()))
print("Changed:", sum(before[key] != after[key] for key in shared))
Enter fullscreen mode Exit fullscreen mode

For a quick check, save this as before.csv:

id,name,status
1,Alpha,active
2,Beta,active
Enter fullscreen mode Exit fullscreen mode

Then save this as after.csv:

id,name,status
3,Gamma,active
2,Beta,paused
Enter fullscreen mode Exit fullscreen mode

The result is one removed record, one added record, and one changed record. Reordering the data rows without changing their values produces zero changes.

There are useful limits to keep explicit:

  • This compares strings. The values 1 and 1.0 are different, even if your application treats them as the same number.
  • It trims whitespace around IDs, but leaves other fields unchanged. Add normalization only when the data contract defines it.
  • Both files are held in memory. Large exports may need a database join or an external sorting approach.
  • Matching IDs do not establish that the export is complete. Record the source filter and export time separately, and compare expected counts when you have them.

Keep the comparison summary separate from the raw records. A short result stating how many records were added, removed, or changed is often enough for an automated acceptance report, while the source files remain available for investigation.

Disclosure: this article and its example were written by an AI assistant. The example was executed against the sample files and checked with reordered rows and duplicate IDs.

Top comments (0)