Reputation: 1
I'm trying to make a basic program that lets the user input a username and password and if it watches one in a file it outputs 'access granted' but the password won't match when compare with the file data even if they are the same
I've tried setting the data saves password as a variable however that hasn't worked
username = str(input('What is your username'))
password = str(input('What is your password'))
accountlogin = 0
file = open('login.txt','r')
for line in file:
seperate = line.split(',')
print(seperate[0])
if username == seperate[0]:
accountlogin = accountlogin + 1
for line in file:
if password == seperate[1]:
accountlogin = accountl`enter code here`ogin + 1
print(accountlogin)
if accountlogin == 2:
print('Access Granted')
correct username so make it equal 3 it does so the password bit must not be working
Upvotes: 0
Views: 47
Reputation: 1492
You can do it using a single loop like below.
username = input('What is your username?')
password = input('What is your password?')
with open('login.txt','r') as f:
for line in f:
user_txt, pass_txt, *_ = line.split(',')
print(user_txt)
if username == user_txt and password == pass_txt:
print('Access Granted')
break
input()
returns str so, casting it to string using str()
is redundant(not necessary). I'm also using the with
keyword for opening the login.txt
file. Read this thread to know more about with
Next, we are splitting lines and taking the first two comma-separated string as username & password respectively from the line and ignoring the rest of the comma-separated strings in the line(if any).
Upvotes: 1
Reputation: 385385
Looping twice has two problems:
After the first loop, the file cursor is at the end of the file. There's nothing left to consume. You could seek back to the start, but…
You check that the username exists anywhere in the file, and independently that the password exists anywhere in the file. You should instead that they exist together in the same record. So put both conditions in the same loop.
Something like this:
username = str(input('What is your username'))
password = str(input('What is your password'))
accountlogin = 0
file = open('login.txt','r')
for line in file:
seperate = line.split(',')
print(seperate[0])
if username == seperate[0]:
accountlogin = accountlogin + 1
if password == seperate[1]:
accountlogin = accountlogin + 1
print(accountlogin)
if accountlogin == 2:
print('Access Granted')
Or even just:
username = str(input('What is your username'))
password = str(input('What is your password'))
file = open('login.txt','r')
for line in file:
separate = line.split(',')
print(separate[0])
if username == separate[0] and password == separate[1]:
print('Access Granted')
break
Also, obligatory note to never store passwords in plain text.
Upvotes: 5