简体   繁体   中英

Python - Comparing two text file and output differences using loops

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```

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM