File and document comparison
Python Compare Two Text Files And Return The Difference
Return the differing lines from two text files with a reproducible example, explicit handling of whitespace and revision direction, and checks before saving the reviewed result.
Decide whether you need an ordered edit report or the set of lines that appears only in one file. They are different outputs. The example below returns unique exact line values from each side; it intentionally ignores line order and repetition counts. Use a unified diff when those properties matter.
Define what “return the difference” means
The example below returns the unique line values present on only one side. It deliberately does not return line numbers, edit operations or repeated occurrences. That is useful for set-like lists. If the caller needs to reconstruct the revised file, this result is insufficient: use an ordered edit representation and specify how unchanged context and final newlines are handled. Name the returned structure so callers cannot mistake one contract for the other.
Return the differing lines from two text files
from pathlib import Path
a = Path("original.txt").read_text(encoding="utf-8").splitlines()
b = Path("revised.txt").read_text(encoding="utf-8").splitlines()
only_original = sorted(set(a) - set(b))
only_revised = sorted(set(b) - set(a))
Path("only-original.txt").write_text("\n".join(only_original), encoding="utf-8")
Path("only-revised.txt").write_text("\n".join(only_revised), encoding="utf-8")Verify a known change
Use original lines apple, banana, apple and revised lines banana, pear. The original-only output is apple once and the revised-only output is pear once. That fixture demonstrates the set behavior explicitly. If two occurrences of apple must be treated separately, use a multiset such as collections.Counter or an ordered diff. A blank line is still a line value; decide whether to retain it.
Choose the right interpretation
The sorted output provides a repeatable order but does not preserve the source positions. Matching is case-sensitive and includes spaces within each line. Do not apply this line-based approach directly to quoted multiline CSV records or arbitrary XML: parse those formats and compare their records or trees instead. If a removed duplicate changes a dataset’s counts, deduplication is a data transformation that requires separate approval from merely generating a difference report.
Keep the comparison reproducible
Label the two inputs Original and Revised and keep those roles consistent. Save a copy of each before experimenting with normalization or accepting changes. A reversed comparison can show the same edit with the opposite insertion/deletion direction, which matters when a reviewer is deciding what to retain. Record the two filenames and the settings used with the result.
Test an identical pair first: it should produce no differences under the chosen contract. Then change one ordinary word, one number and one punctuation mark in the revised copy. Verify each known change before using an unfamiliar document. Include a blank line and a moved paragraph so you can see whether the method reports a move or a deletion followed by an insertion. Those presentations may describe the same underlying edit.
Decide whether spaces, capitalization and line endings matter before normalizing them. Ignoring every space can hide a meaningful change in code, a quoted value or a fixed-width record. Case folding is useful for some lookup tasks but is wrong for case-sensitive identifiers. Retain the unmodified inputs alongside any normalized copies so a surprising result can be investigated rather than explained away.
Review the complete changed region, including its surrounding context. An inserted “not,” a removed qualification or a changed unit can reverse a statement while contributing very few changed characters. Conversely, a formatter can change many lines without changing an application’s intended behavior. A difference count describes the chosen representation; it does not by itself measure importance, quality, originality or semantic equivalence.
Finish the review deliberately
For each meaningful difference, decide whether to keep the original, keep the revised version or write a new combined version. Save that reviewed result under a new filename and compare it again with the intended baseline. Do not overwrite the only original while you are still interpreting the report. Keep a short record of unresolved differences when the review is handed to another person.
Use only files you are authorized to inspect. If a web tool is involved, read its stated processing behavior and file limits before supplying confidential material. A local comparison can avoid uploading the content, but browser downloads, clipboard history and shared-device storage still need ordinary care. Clear temporary copies according to your own retention needs after the review is complete.
Primary reference
Official comparison documentation


