Python 3.5+difflibfunction
difflib.diff_bytes()
diff formats
A wrapper that lets unified_diff and context_diff compare bytes lines whose encoding is unknown.
Syntax
difflib.diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', n=3, lineterm=b'\n')
unified_diff and context_diff themselves raise TypeError on bytes. diff_bytes decodes everything with surrogateescape, compares and encodes back, so undecodable bytes pass through intact. All the other arguments, file names, dates and lineterm, must be bytes as well. Added in Python 3.5.
Examples
import difflib
a = [b'caf\xe9\n']
b = [b'cafe\n']
print(list(difflib.diff_bytes(difflib.unified_diff, a, b, b'a', b'b'))[3:]) # → [b'-caf\xe9\n', b'+cafe\n']
import difflib
try:
list(difflib.unified_diff([b'x'], [b'y']))
except TypeError as e:
print(e) # → lines to compare must be str, not bytes (b'x')
See also
Open in the full glossarydocs.python.orgReport an inaccuracy