Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two files using difflib in python

I am trying to compare two files using difflib. After comparing I want to print "No Changes" if no difference detected. If difference is their in some lines. I want to print those line.

I tried like this:

with open("compare.txt") as f, open("test.txt") as g:
            flines = f.readlines()
            glines = g.readlines()
        d = difflib.Differ()
        diff = d.compare(flines, glines)
        print("\n".join(diff))

It will print the contents of the file if "no changes" are detected. But I want to print "No Changes" if there is no difference.

like image 220
Krishna Avatar asked Dec 06 '25 03:12

Krishna


1 Answers

Check to see if the first character in each element has a + or - at the start (marking the line having changed):

with open("compare.txt") as f, open("test.txt") as g:
        flines = f.readlines()
        glines = g.readlines()
        d = difflib.Differ()
        diffs = [x for x in d.compare(flines, glines) if x[0] in ('+', '-')]
        if diffs:
            # all rows with changes
        else:
            print('No changes')
like image 62
David C Avatar answered Dec 07 '25 18:12

David C