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.

1
  • Have you looked at the answers to this question? Commented Oct 10, 2015 at 6:17

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for ur help. But its printing nothing
THANK YOU David, I got the result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.