Generate unified text differences with difflib.unified_diff().
How It Works
unified_diff(old_lines, new_lines, fromfile, tofile) yields context lines with - and + markers. Input lines should retain line endings when appropriate, and the function returns an iterator of strings.
Step-by-Step Example
import difflib
old_lines = ['one\n', 'two\n']
new_lines = ['one\n', 'three\n']
changes = list(difflib.unified_diff(old_lines, new_lines, fromfile='before', tofile='after'))
print(any(line.startswith('-two') for line in changes))
print(any(line.startswith('+three') for line in changes))
Understanding the Example
- The expression "['one\\n', 'two\\n']" supplies the value stored as 'old_lines'. This value is then used or checked by the later statements.
- The expression "['one\\n', 'three\\n']" 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:
True
True
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
unified_diff generates a textual comparison, not a patch application mechanism.
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
- Passing large unsplit strings and expecting sensible line-based diff output.
- Show the changes between two configuration file versions.
Key Takeaways
- Generate unified text differences with difflib.unified_diff().
- unified_diff(old_lines, new_lines, fromfile, tofile) yields context lines with - and + markers.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.