all Python 3difflibfunction
difflib.unified_diff()
diff formats
Builds the differences between two lists of lines in unified diff format, like git diff: -, + lines and @@ headers.
Syntax
difflib.unified_diff(a, b, fromfile='', tofile='', n=3, lineterm='\n')
It takes lists of lines, not text: a whole string would be compared character by character. The line ending trap: for a list from splitlines() the headers get an extra '\n' and the output goes ragged, so pass lineterm=''. It returns a generator, which is empty for equal inputs. Only n=3 lines of context are shown.
Examples
import difflib
a = ['one\n', 'two\n', 'three\n']
b = ['one\n', 'too\n', 'three\n']
print(''.join(difflib.unified_diff(a, b, 'old.txt', 'new.txt')))
# → --- old.txt / +++ new.txt / @@ -1,3 +1,3 @@ / -two / +too
import difflib
old = 'x = 1\ny = 2'.splitlines()
new = 'x = 1\ny = 3'.splitlines()
for line in difflib.unified_diff(old, new, 'v1', 'v2', lineterm=''):
print(line) # → --- v1 / +++ v2 / @@ -1,2 +1,2 @@ / -y = 2 / +y = 3
See also
Open in the full glossarydocs.python.orgReport an inaccuracy