I have 2 txt files like this:
fileA: fileB:
0 0
5 0
0 80
20 10
600 34
I need to compare the numbers in these 2 lists respecting the position in the list. I need to generate an output file with the comparison for each of the lines like:
Output:
E
A
B
A
A
I have tried something like:
lineA = [lineb.rstrip('\n') for lineb in open("fileA.txt")]
lineB = [lineb.rstrip('\n') for lineb in open("fileB.txt")]
for i in lineA:
for u in lineB:
if lineA[i] > lineB[i]:
print("A")
elif lineA[i] < lineB[i]:
print("B")
elif lineA[i] == lineB[i]:
print("E")
but the loop is not able to work properly. I've tried also to convert first the list in integers ( in case they are not recognized ad int) like:
for w in range(0, len(lineA)):
lineA[w] = int(lineA[w])
print(str(lineA))
BUT I CAN'T SOLVE THE PROBLEM...
You can use zip
to loop through the two lists in parallel:
# use `with` to automatically close the files after reading
with open("fileA.txt") as file_a, open("fileB.txt") as file_b:
# use `int` in the list comprehension
# and, use `.rstrip()` if you just want to remove whitespace
lineA = [int(line.rstrip()) for line in file_a]
lineB = [int(line.rstrip()) for line in file_b]
for i, u in zip(lineA, lineB):
if i > u:
print("A")
elif i < u:
print("B")
else:
print("E")