Reputation: 11
The first file: This is text./n abc/n 123
The second file: This is text./n xyz/n 123
I'm doing an assignment that is asking me to print("No") while also printing the part of the line that is different in both the first and second file if the file is different. They are asking me to use loops to compare and find the difference than to print the differences and break the loop if the differences are found. I can't seem to get to the second line of text to make my condition true.
secondFile = input("Enter the second file name: ")
first = open(firstFile, 'r')
second = open(secondFile, 'r')
if first.read() == second.read():
print("Yes")
else:
print("No")
while True:
firstLine = first.readline()
secondLine = second.readline()
if firstLine == secondLine:
print(first.readline())
print(second.readline())
break```
Upvotes: 0
Views: 313
Reputation: 50899
second.read()
consimes all the data from the file, so once you reach first.readline()
you get only empty strings. Read the file line by line and print "Yes" only if all the lines where already compare using for else
. You should also close the files once done, you can do it by using with
with open(firstFile, 'r') as file1, open(secondFile, 'r') as file2:
for line1, line2 in zip(file1, file2):
if line1 != line2:
print('No', line1, line2, sep='\n')
break
else:
print('Yes')
Upvotes: 1