Skip to content
Advertisement

python – read .txt file line by line

I am trying to read every line of my file which contains a list of usernames and than make a login system with it. I am trying to implement a basic login system which has usernames stored in a .txt file but my code doesn’t work and I don’t know why. I think that the problem is in my loop which checks for username.

Here is my code but it doesn’t work it just prints fail all the time:

a = input('do you have an account y/n:')
 

if a == 'y':
    b = input('insert username:')

    file1 = open('file.txt', 'r')
    lines = file1.readlines()

    for line in lines:
        if not lines:
            pass 
            if line == b:
                print('pass')

    else:
        print('fail')

else:
    d = input('new username:')

    f = open("file.txt", "a")
    print(d, file=f)
    f.close()

Any ideas?

Advertisement

Answer

for line in lines:
    if not lines:
        pass 
        if line == b:
            print('pass')

If the file has any contents, if not lines will never be true. And since if line == b is indented underneath that, it never gets executed.

Also, when you iterate over the lines in a file like that, line will have a newline character at the end, so if line == b would not be true anyway. You’ll have to strip off the newline character.

Try this instead:

for line in lines:
    if line.strip() == b:
        print('pass')
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement