4

Is there an easy way to compare 2 files in Python while ignoring certain lines? I want to ignore Python style comments (a line beginning with #) and check if all other lines are the same. I guess there's always reading the file line by line and manually comparing.

2 Answers 2

3

First remove the comments from both files. Then use a Differ to compare the resulting files.

Sign up to request clarification or add additional context in comments.

Comments

2

Do you just want to report if they are the same or are different? Or do you also want to know the first place where they are different, or do you want to know all of the places where they are different?

I'll assume you want to know the first line where they are different. First, a helper function to read the non-comment lines, and to include line number information:

def read_non_comment_lines(infile):
    for lineno, line in enumerate(infile):
        if line[:1] != "#":
            yield lineno, line

Compare two input streams and report when they are different:

import itertools
with open(filename1) as f1:
    with open(filename2) as f2:
        for (lineno1, line1), (lineno2, line2) in itertools.izip(
                       read_non_comment_lines(f1), read_non_comment_lines(f2)):
            if line1 != line2:
                print "Different at %s:%d and %s:%d" % (filename1, lineno1+1, filename2, lineno2+1)
                break
        else:
            print "They are identical."

2 Comments

Reporting whether they're the same or different is fine. Thanks!.
That case is simpler. It's the same code as above, only without the line number tracking.

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.