The context_diff() function of Python difflib module

Overview:

  • The function context_fiff() emulates the behavior of the diff command invoked with the -c or -C switch.

diff -C <context line count > <fromfile> <tofile>    

The context format of diff command:

  • The context difference format lists a block of changes in fromfile followed by a block of changes in tofile. In This scheme of listing the changes using pairs of blocks the first pair of the block depicts fromfile changes and the second pair of the block depicts tofile changes. The blocks continue till both the files are exhaust.
  • The lines without any prefix are the ones that have not changed. These lines are the context lines.
  • In context format, the context lines are shown both in fromfile changes and tofile changes. On the contrary the unified format shows the changes in both files using single blocks thus avoiding redundancy of context lines.
  • The prefix “+” denotes an added line and a “-” denotes a deleted line. The prefix “!” shows an intra-line change.

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