meteoritepanama
meteoritepanama

Reputation: 6242

Comparing 2 files in Python while ignoring comments

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.

Upvotes: 4

Views: 1593

Answers (2)

Andrew Dalke
Andrew Dalke

Reputation: 15305

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."

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838156

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

Upvotes: 3

Related Questions