3

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.

Krishna
  • 45
  • 2
  • 6
  • Have you looked at the answers to [this question](http://stackoverflow.com/questions/977491/comparing-2-txt-files-using-difflib-in-python)? – David C Oct 10 '15 at 06:17

1 Answers1

3

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')
David C
  • 7,204
  • 5
  • 46
  • 65