user9323924
user9323924

Reputation: 77

How to compare and count the differences between two files line by line?

I need to compare two files line by line. In each file, the line just has either 1 or -1 so if the lines are the same, don't count and if it's different then count =+1.

For example:

File1 line1= 1 , file2 line1 =-1 then count = 1

File1 line2= 1 , file2 line2 =1 Don't count, so count stays 1

I am trying to write it in Python and I know how to readlines in a single file but I am really struggling comparing two files line by line and spotting the difference.

How can this be done? Thanks for your time

Upvotes: 1

Views: 1545

Answers (2)

Trap
Trap

Reputation: 228

You can use zip (https://docs.python.org/3.3/library/functions.html#zip)

count = 0

with open(file1name) as file1, open(file2name) as file2:
    for line_file_1, line_file_2 in zip(file1, file2):
        if line_file_1 != line_file_2:
            count += 1

Note that this example assumes that your files have the same number of lines. Also, this question has already been answered here : How to iterate across lines in two files simultaneously?

Upvotes: 0

tdelaney
tdelaney

Reputation: 77337

Files are their own iterators, zip will read them together line by line, booleans are also 0 and 1 and sum adds them all together. So...

print(sum(zipline[0]!=zipline[1] 
    for zipline in zip(open('file1'), open('file2'))))

Upvotes: 3

Related Questions