简体   繁体   中英

trying to figure out how to get the next values using a loop in python

I am looking for some resource, my code print the first unequal value between two txt files. what I am trying to do is how to get to the next unequal values if I press a key. I think the while loop would help, but I fail in every logic. any resource where I could find some answers?

def textdiff():
    text1 = open("text1.txt", "r")
    text2 = open("text2.txt", "r")
    for orgtext1 in text2:
        for oldtext2 in text1:
            if oldtext2 != orgtext1:
                return oldtext2
        text1.close()
        text2.close()


print(textdiff())

thanks a lot

If you want to compare the nth character of file 1 with the nth character of file 2, I would useyield to jump out of the function after each found inequality and the with statement to make sure that the files are properly closed if an error is raised:

def textdiff():
    with open("text1.txt", "r") as file1:
        with open("text2.txt", "r") as file2:
            text1 = file1.read()
            text2 = file2.read()
            shared_length = min(len(text1), len(text2))
            for pos in range(shared_length):
                if text1[pos] != text2[pos]:
                    yield text1[pos] + " != " + text2[pos]

for diff in textdiff():
    print(diff)
    input('Press <Return> to continue')

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