Username search in file python - python

I am trying to find a username from a txt file. (I know it is not security wise, but it is for testing purposes) Below is my code I am using and where I find the username from any line in file, save it to a list and then verify the password from that list. But it only finds the first line in file. All the other usernames after line 1 gets "Username not found"
with open("user.txt","r") as file:
for line in file.readlines():
login_info = line.rstrip("\n").split(", ")
while True:
username = input("Please enter your username: ")
if username == login_info[0]:
print("Username found!\n")
while True:
password = input("Please enter your password: ")
if password == login_info[1]:
print("Password correct!\n")
print(f"Welcome {username}!\n")
return options()
else:
print("Password incorrect.")
else:
print("Username not found.")
The txt file looks like this:
admin, adm1n
pete, p3t3
mark, m#rk
Where each line has the username as first string followed by comma and then the password.
If anyone could help me or point me in the right direction for answers.

There are multiple issues with your code like you are opening the file 2 times, which is unneccessary, secondly you need to check the user provided username against all the username not only login_info[0]
You can try something like
username_password_map = {}
with open('user.txt') as f:
for line in f.readlines():
username, password = line.rstrip('\n').split(', ')
username_password_map[username] = password
username = input("Please enter your username: ")
if username in username_password_map:
while True:
password = input("Please enter your password: ")
if password == username_password_map[username]:
print("Password correct!\n")
print(f"Welcome {username}!\n")
break
else:
print("Password incorrect.")
else:
print("Username not found.")

Related

How do i make a login signup system in python?

im trying to write code in python that basically its so that in the terminal you input whether you want to signup or log in if you already signed up
i cant really figure out how to make it so that the signup input gets stored in a dictionary and then later when you try to enter the username and password it makes sure its the same one from the signup feature
thanks in advance
so far ive tried
accounts = {"user":"password", "user2":"password2"}
login_or_signup = input("Login or signup? ")
if login_or_signup.upper() == 'LOGIN':
username = input("Enter your username: ")
if username in list(accounts.keys()):
password = input("Enter your password: ")
if password in list(accounts.values()):
print("Logged in successfully.")
else:
print("Account credentials do not match.")
else:
print("Account not found.")
elif login_or_signup.upper() == "SIGNUP":
username = input("Enter your username: ")
password = input("Enter your password: ")
accounts.update({user,password})
but im getting an error
You have a typo in your last line, it should be username instead of user. Also : instead of ,
accounts.update({username: password})
That will make your program not fail in both options.
However, first, you are not checking properly the password, you need to grab the user and check if the password corresponds to the user in your dictionary.
Additionally, your program will finish right after you set up your new signup. You can add a while True loop at the top and break accordingly in the condition you would like to do so (example)
You should check if input password, matches the input username.
accounts = {"user": "password", "user2": "password2"}
login_or_signup = input("Login or signup? ")
while True:
if login_or_signup.upper() == 'LOGIN':
username = input("Enter your username: ")
if username in accounts:
password = input("Enter your password: ")
if accounts[username] == password:
print("Logged in successfully.")
else:
print("Account credentials do not match.")
else:
print("Account not found.")
elif login_or_signup.upper() == "SIGNUP":
username = input("Enter your username: ")
password = input("Enter your password: ")
accounts[username] = password

Is there any reason why this code wouldnt work at the start of of some Python code?

This code is at the start and when I run the code it doesn't do anything and nothing shows up, please help?
users = {}
status = ""
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
if login():
print("You are now logged in...")
else:
print("You aren't logged in!")
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
I expect the output to be a login system that then leads to a quiz but when I run it all I get is blank space
All you're doing is creating a couple of variables and declaring some functions.
Neither of those things will result in any output. If you want the functions to run, you'll actually need to call them from somewhere, such as by putting register() or login() (with no indentation) after the function definitions.
You defined the functions, but didn't call either, you should call one or both at the end of your script like :
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False
login()

Saving multiple usernames and passwords in an external file for python

My Current code is a simple 1 username and 1 password consistency.
I wish to find the most simple and effective way to store several different passwords in e separate file form the python program and allow them to be used and if correct, allow the user to access the rest of the code.
The code is as follows currently it does work but i'm trying to find a more intricate way as i said above:
loggedin = False
while loggedin == False:
username = input("Username:")
password = input("Password:")
if password == "Player1" and username == "Player1":
print ("Logged in as Player1")
loggedin = True
else:
print ("Incorrect Password. Please try again.")
You could setup your program with conditions where 'Enter password: ' is only prompted if Username exists in the stored file, then you can check then password to see if it exists on the same line as username assuming we have a info.txt file with the each username and password stored on its own line
info.txt
vash stampede
Code
loggedin = True
while loggedin:
with open('info.txt') as f:
username = input('Username: ')
for line in f:
if username in line:
password = input('Enter password: ')
if password in line:
print('Welcome')
loggedin = False
else:
print('Password Invalid')
else:
print('Username not found.')
Output
Username: someone
Username not found.
Username: vash
Enter password: stampede
Welcome

List Index Error out of range

When I run my code I get this message:"in Login if username == login_info[0] and password == login_info[1]: IndexError: list index out of range"My code used to work before but I don't understand why it doesn't work anymore.
#Registration
def Register():
username = input("Please input the first 3 or 4 letters of your first name and your year: ")#Gets the user to create a username
validate()#Calls upon the password validate()
file = open("AccountFile.txt","a") #Opens the text file called "AccountFile"
file.write(username)#Writes the users username into the text file.
file.write(" ")
file.write(password)#Writes the users password into the text file.
file.write("\n")
file.close()#Closes the text file "AccountFile"
#Login
def Login():
username = input("Please enter your username: ") #Asks the user to enter their username that they created
username = username.strip() #Any spaces that the user may put in will not affect the code and be removed
password = input("Please enter your password: ") #Ask the user to enter their password that they created
password = password.strip()
for line in open("AccountFile.txt","r").readlines(): #Reads the lines in the text file "AccountFile"
login_info = line.split() #Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print("You have succesfuly logged in!") #Lets the user know that they have succesfully logged in
return True
print("Incorrect credentials.")
return False
#Validation
def validate():
while True:
global password #Makes the password global meaning the function global can be called upon anywhere in the code
password = input("Enter a password: ") #Asks the user to create a password
password = password.strip()
if len(password) < 8: #Checks whether the password is at least 8 letters long
print("Make sure your password is at least 8 letters")
elif re.search('[0-9]',password) is None: #Makes sure that the password has a number in it
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None: #Makes sure the password has a capital letter in it
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
#DisplayMenu
def DisplayMenu():
status = input("Are you a registered user? y/n? ") #Asks the user if they already have a registered account
status = status.strip()
if status == "y":
Login()
elif status == "n":
Register()
DisplayMenu()

How to check text file for usernames and passwords

I'm writing a program which will need a user to register and login with an account. I get the program to have the user make their username and password which are saved in an external text file (accountfile.txt), but when it comes to the login I have no idea how to get the program to check if what the user inputs is present in the text file.
This is what my bit of code looks like :
def main():
register()
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.close()
login()
def login():
check = open("accountfile.txt","r")
username = input("Please enter your username")
password = input("Please enter your password")
I have no idea what to do from this point.
Also, this is what a registered account would look like in the text file:
Ha2001 examplepassword
After opening the file, you can use readlines() to read the text into a list of username/password pairs. Since you separated username and password with a space, each pair is string that looks like 'Na19XX myPassword', which you can split into a list of two strings with split(). From there, check whether the username and password match the user input. If you want multiple users as your TXT file grows, you need to add a newline after each username/password pair.
def register():
username = input("Please input the first 2 letters of your first name and your birth year ")
password = input("Please input your desired password ")
file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
if login():
print("You are now logged in...")
else:
print("You aren't logged in!")
def login():
username = input("Please enter your username")
password = input("Please enter your password")
for line in open("accountfile.txt","r").readlines(): # Read the lines
login_info = line.split() # Split on the space, and store the results in a list of two strings
if username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
return True
print("Incorrect credentials.")
return False

Categories