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.