Search code examples
pythondifflib

Using context_diff print only lines which have differences


I have the below code which prints the differences between two files and I have used context_diff from difflib module.

import difflib

file1 = open(“filename1.json”,”r”)
file2 = open(“filename2.json”,”r”)

diff = difflib.context_diff(file1.readLines(), file2.readLines())
delta = ‘’.join(diff)
print(delta)

filename1.json

{ 
“Name” : “John”,
“Occupation” : “Manager”, 
“Age” : 35,
“Company” : “vTech”
}

filename2.json

{ 
“Name” : “Mel”,
“Occupation” : “Developer”, 
“Age” : 35,
“Company” : “vTech”
}

I want only the lines which have differences to be printed. Is there anyway we can do that? If so please suggest. Thanks I’m advance.

Expected output:


! “Name” : “John”,

! “Occupation” : “Manager”,


! “Name” : “Mel”,

! “Occupation” : “Developer”,


Actual output


! “Name” : “John”,

! “Occupation” : “Manager”,

“Age” : 35,

“Company” : “vTech”


! “Name” : “Mel”,

! “Occupation” : “Developer”,

“Age” : 35,

“Company” : “vTech”



Solution

  • From the docs:

     difflib.context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
    

    Context diffs are a compact way of showing just the lines that have changed plus a few lines of context. The changes are shown in a before/after style. The number of context lines is set by n which defaults to three.


    Try to set n to 0 to display no context:

    diff = difflib.context_diff(file1.readLines(), file2.readLines(), n=0)