The context_diff() method of htmldiff class

Overview:

  • The context diff format returned by the context_diff() method is same as the one emitted by the GNU diff tool.
  • The context diff format marks the changed lines with a ! symbol, leaving the unchanged lines without any marking. The GNU diff tool shows few lines of context around the text that has changed.

Example:

# Example Python program that displays the 
# difference between lines of text in context diff format
# using difflib.context_diff() function

import difflib

# Text lines to be compared
# Few lines from the poem 
# “Do Not Go Gentle Into That Good Night” by Dylan Thomas
text1 = ["Because their words had forked no lightning they",
         "Do not go gentle into that good night."]

text2 = ["And learn, too late, they grieved it on its way,",
         "Do not go gentle into that good night."]

# Find the differences in context diff format
contextDiff = difflib.context_diff(text1, text2,
                                   fromfile = "from.txt",
                                   tofile = "to.txt")
print("The contextual difference:")
print(contextDiff)

# Print the differences in context diff format
for line in contextDiff:
    print(line)

Output:

The contextual difference:
<generator object context_diff at 0x1017c28c0>
*** from.txt

--- to.txt

***************

*** 1,2 ****

! Because their words had forked no lightning they
  Do not go gentle into that good night.
--- 1,2 ----

! And learn, too late, they grieved it on its way,
  Do not go gentle into that good night.

 


Copyright 2026 © pythontic.com