Compare two CSV files

How to find the differences between two CSV files: line-based diff versus keyed record comparison, what each one detects, and pitfalls with row order, encoding and sensitive data.

What a CSV comparison actually compares

A CSV file is plain text. Each line usually holds one record, and fields are separated by commas. TSV files use tabs instead. When you diff two CSV files, the tool compares them at a particular level, and that level decides what counts as a difference.

  • Text level: lines are compared as strings. Any change in a line, including a moved row or a different quote style, shows up as a difference.
  • Record level: rows are matched by a key, such as an ID column. The tool then reports which records were added, removed or kept, regardless of where they appear in the file.
  • Field level: within matched records, individual cells are compared. You learn which column changed and its old and new values.

A line is not always a record. A quoted field can contain commas or line breaks, and a text-level tool will treat those as ordinary characters or extra lines. Comparing never modifies either file; the output is a separate report. Some tools normalize values before comparing, for example by trimming spaces or ignoring case. Normalization changes what gets reported, not the files themselves.

An illustrative example

The two files below are used throughout this guide. The outputs described afterward are illustrative explanations of how each approach behaves. They are not captured runs of any specific tool.

old.csv
id,name,city
1,Ana,Denver
2,Ben,Austin
3,Cara,Boston

new.csv
id,name,city
3,Cara,Boston
1,Ana,Dallas
4,Dev,Miami

A line-based diff sees the reordering of row 3 as a removal in one place and an addition in another. It shows "1,Ana,Denver" removed and "1,Ana,Dallas" added, with no indication that only the city changed. It also reports row 2 removed and row 4 added. The exact grouping depends on the diff algorithm.

A comparison keyed on id reports three things. Record 1 changed its city from Denver to Dallas, record 2 was removed and record 4 was added. Record 3 is unchanged because its position in the file is ignored.

Which approach suits your result

Approach | What it reports | Affected by row order | Affected by column order | Best fit
Line-based text diff | Added and removed lines | Yes | Yes | Small files from the same export process; reviewing changes in version control
Sort, then line diff | Lines present in only one file | No, after sorting | Yes | Checking which rows exist in one file but not the other when no key column exists
Keyed record comparison | Added, removed and changed records, with field detail | No | No, if columns are matched by header name | Data reconciliation, audits, and reports someone else must act on
Spreadsheet side by side or lookup formulas | Whatever you build visually or with formulas | Depends on setup | Depends on setup | Quick, one-off checks on small files

Each approach involves a tradeoff. A text diff needs no setup and preserves the exact raw characters, but it does not understand records. Sorting removes order noise, but a changed row still appears as one removal plus one addition. A keyed comparison gives the most useful report. It requires a column that uniquely identifies each row, plus a few decisions about how to treat formatting differences.

Line-based diff

diff old.csv new.csv

# Highlight changes per comma-separated field instead of per whole line
git diff --no-index --word-diff-regex='[^,]+' old.csv new.csv

The second command treats each run of non-comma characters as a word. As a result, a single changed cell is highlighted within its line. The command does not account for commas inside quoted fields.

Order-insensitive check without a key

LC_ALL=C sort old.csv > old.sorted
LC_ALL=C sort new.csv > new.sorted
comm -3 old.sorted new.sorted

The comm command needs sorted input. With -3, it hides lines common to both files. Lines found only in the first file appear in the first column, and lines found only in the second file appear indented by a tab. Setting the same locale for both sorts keeps the ordering consistent. The header line gets sorted along with the data, so remove it first if it would get in the way.

Keyed comparison with a short script

import csv

def load(path, key):
    with open(path, newline='', encoding='utf-8') as f:
        return {row[key]: row for row in csv.DictReader(f)}

old = load('old.csv', 'id')
new = load('new.csv', 'id')

for k in sorted(old.keys() - new.keys()):
    print('removed', k)
for k in sorted(new.keys() - old.keys()):
    print('added', k)
for k in sorted(old.keys() & new.keys()):
    for col in old[k]:
        if old[k][col] != new[k].get(col):
            print('changed', k, col, repr(old[k][col]), '->', repr(new[k].get(col)))

Python's csv module parses quoted fields correctly, so embedded commas and line breaks do not break the comparison. The script has three limits. Duplicate keys overwrite each other without warning, columns that exist only in the new file are not checked, and both files are held in memory. Before relying on the report, confirm that the key really is unique.

Decisions to make before comparing

Many reported differences turn out to be formatting rather than data. Decide in advance which of these should count.

  • Delimiter: comma, semicolon or tab. A file exported with a different separator will not parse as the same data.
  • Encoding and byte order mark: a UTF-8 file with a BOM can make the first header name differ invisibly.
  • Line endings: CRLF and LF lines differ at the text level even when the content is identical.
  • Quoting: "Ana" and Ana hold the same value but are different text.
  • Whitespace and case: trailing spaces and letter case may or may not be meaningful for your data.
  • Number and date formats: 1.0 versus 1, or 2026-10-31 versus 10/31/2026.
  • Empty versus missing: an empty cell and an absent column are not the same thing.
  • Header names: renamed or reordered columns need to be mapped before a field-level comparison.

Will the comparison output be usable where you need it?

Diff viewers often mark changes with color alone. Color is lost when output is pasted into plain-text destinations, and it is hard to read for people with color vision differences. Screen reader users also get little from color. Prefer outputs that use explicit markers, such as the + and - prefixes of standard diff output, or a column that names the change type.

Terminal diff output can lose its alignment when pasted into email or chat. The most portable report is itself a CSV with columns such as key, column, old_value, new_value and change_type. Before sharing a report, open it in the destination where it will be read and check that it displays as intended.

Opening CSV files in a spreadsheet application can change values on import. Leading zeros may be dropped, long numbers may be shortened, and date-like strings may be converted to dates. If exact values matter, compare the raw files or import every column as text.

Online CSV comparison services require uploading both files to someone else's server. If the files contain personal, financial or confidential data, check whether you are permitted to share them, and prefer a local tool. Hashing identifiers before upload does not reliably anonymize short or predictable values such as phone numbers or postal codes.

Quick decision guide

  • Same export process and stable row order: use a line-based diff.
  • No key column, and you only need to know which rows exist in one file but not the other: sort both files, then compare.
  • You need to know which fields changed in which records: use a keyed comparison.
  • Files contain sensitive data: run the comparison locally.
  • The report will be shared or reviewed by others: produce a CSV report with explicit change labels instead of color-only output.

Gaps in this guide: no measured performance figures, file-size limits or tested outputs from specific products were available. The behavior described for the examples is illustrative, and any particular tool should be verified on a sample of your own data.