Read a specific line from a text file then check if it's equal to a string variable?

Viewed 550

I am trying create a login system. The user creates their account and inputs the username and password they would like to use.

The username gets stored in line 1 of a new text file.

The password gets stored in line 2 of the text file.

Now I open the file and make it readable

user_file = open("user1.txt", "r")

Then I have the user enter the username created earlier.

username_login = input("Enter username ")

Now I want check to see if the username submitted is the one stored on line 1

if user_file.readline(1) != username_login:
        print("Incorrect username")
    else:
        password_login = input("Enter Password ")

If the username submitted is correct it would match line 1 and therefore print the else statement. but instead I always get the "incorrect username" feedback

3 Answers

Assuming the file consists of just 2 lines, what you could do is extract username and password and then compare them with input's data. Example:

with open('user1.txt') as f:
   username, password = f.read().splitlines() 
# now compare username and password with input data

Go through your file with a for loop:

for line in user_file.readlines():
    if line[0] == username:
        #do something

As Ryan said, this is definitely not the way that logins should be managed in reality, but assuming this is just practicing python...

First, note that python indices start at 0, so the first line would be called line 0. I also don't believe readline() accepts a parameter to make it do what you want. Instead, one solution could be to store the file contents into a list which can be indexed:

lines = user_file.readlines()
username_login = input("Enter username ")
if lines[0].strip('\n') != username_login:
    print("Incorrect username")
else:
    password_login = input("Enter Password ")

and then to access the password you can do lines[1]

Related