all Python 3difflibfunction
difflib.context_diff()
diff formats
Builds differences in context diff format: *** and --- blocks with ! marking changed lines.
Syntax
difflib.context_diff(a, b, fromfile='', tofile='', n=3, lineterm='\n')
The format predates unified diff and is twice as wordy: each changed region is shown twice, before and after. Today only old tools (patch -c) expect it; people and git are used to unified_diff. The traps are the same: the input is lists of lines, lines without '\n' need lineterm='', and the result is a generator.
Examples
import difflib
a = ['one\n', 'two\n', 'three\n']
b = ['one\n', 'too\n', 'three\n']
print(''.join(difflib.context_diff(a, b, 'old.txt', 'new.txt')))
# → *** old.txt / --- new.txt / *** 1,3 **** / ! two / --- 1,3 ---- / ! too
See also
Open in the full glossarydocs.python.orgReport an inaccuracy