Compare two texts with line-oriented differences rather than printing both files.
How It Works
difflib.unified_diff() produces an understandable patch-like representation: unchanged context, removed lines prefixed by minus signs and added lines prefixed by plus signs. Read files with a consistent encoding and preserve line terminators when computing diff.
For confidential files, avoid publishing a diff that includes passwords or tokens.
Step-by-Step Example
import difflib
old_lines = "name=tool\nmode=fast\n".splitlines(keepends=True)
new_lines = "name=tool\nmode=safe\n".splitlines(keepends=True)
changes = list(difflib.unified_diff(old_lines, new_lines, fromfile="old.txt", tofile="new.txt"))
print("".join(changes))
Understanding the Example
- The expression '"name=tool\\nmode=fast\\n".splitlines(keepends=True)' supplies the value stored as 'old_lines'. This value is then used or checked by the later statements.
- The expression '"name=tool\\nmode=safe\\n".splitlines(keepends=True)' supplies the value stored as 'new_lines'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
--- old.txt
+++ new.txt
@@ -1,2 +1,2 @@
name=tool
-mode=fast
+mode=safe
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
Add a third configuration line and explain how the diff distinguishes additions from replacements.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Removing all newlines before diffing and producing confusing, run-together output.
- Treating a text diff as proof that arbitrary binary files are the same.
Key Takeaways
- Compare two texts with line-oriented differences rather than printing both files.
- difflib.unified_diff() produces an understandable patch-like representation: unchanged context, removed lines prefixed by minus signs and added lines prefixed by plus signs.
- For confidential files, avoid publishing a diff that includes passwords or tokens.