File comparison program in python

2

I have a question and a great difficulty creating a program that reads 2 files, example doc1.txt and doc2.txt , inside the files it has the following data:

doc1.txt   doc2.txt
1            1
1            2
2            5
3            6
4            7
5            7
10           8
             9

It should be line by line and compare, example if data 1 of doc1 is == to data 1 of doc2, doc1 > doc2 or

asked by anonymous 04.07.2018 / 03:26

1 answer

1

As commented out, the problem of reading only the first line is that you used the readline method, which reads only one line. To read all, you will need to iterate over the file with a loop repetition.

As explained in What is the purpose of with in Python? , you can use multiple context managers in the same with , which would simplify your program:

with open('entrada_1.txt') as arquivo_1, \
     open('entrada_2.txt') as arquivo_2, \
     open('saida.txt', 'w') as saida:
    numeros_arquivo_1 = (int(numero.strip()) for numero in arquivo_1)
    numeros_arquivo_2 = (int(numero.strip()) for numero in arquivo_2)
    for a, b in zip(numeros_arquivo_1, numeros_arquivo_2):
        saida.write(f'{a}\n' if a >= b else f'{b}\n')

Since you are reading a file, it is natural for the data to come as string , so you need to convert it to numeric. The numeros_arquivo_1 objects and numeros_arquivo_2 objects are exactly that - strip is to remove the line break.

With zip , we group the values of the two files to make it easier to compare a to b . If the value in file 1 is greater than or equal to that of file 2, the value of a is written to the output file, otherwise, the value of b is written. It is important to note that zip uses the smallest file as a reference, ignoring the extra values of the greater. If you need to compare based on the largest file, use the itertools.zip_longest function.

    
04.07.2018 / 13:45