Skip to content
Advertisement

comparing multiple lines of a txt file to a single variable in python

I want to know how to compare multiple lines of a text file to a single variable. I have got it partially working but it only compares to last line of text file

def loginSetup():
    global loginSelector
    global accountInt
    loginSelector = int(input("Select Action:"))    
    
    if loginSelector == 1:
        #login
        print ("action complete")

    if loginSelector == 2:
        #sign up  
        accountInt = int(input("Input 4 Digit Pin:"))
        while (accountInt >= 9999 or accountInt <= 999):
            print("ERRORnTry Again")
            accountInt = int(input("Input 4 Digit Pin:"))
        accountInt = str(accountInt)
        with open('Account.txt', 'r') as rf:
            for line in rf:
                if (line == str(accountInt)):
                    print("error")
        with open('Account.txt', 'a') as f:
            f.write('n')
            f.write(accountInt)
            



while True: 
    loginSetup()        

Advertisement

Answer

That’s because rather than the standard way of writing a line of text followed by a newline, you’re writing the newline first. So the last line of the file doesn’t have a trailing newline (and allows the comparison to succeed there).

In the loop, line will be some text with a newline at the end (for all but the last line), and str(AccountInt) will never have a newline. So no match is possible.

You’ll want to strip the newline from your string before comparing.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement