Code will only read the first line of a text file - python

So I copied some code over from another post on here, but i cant get it to read any lines after the first, im trying to make a username and password system.
def register(): #This function has been adapted from www.stackoverflow.com
print("Please register.")
time.sleep(1)
username = input("Please input your desired username: ")
password = input("Please input your desired password: ")
file = open("outputusernamefile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write("\n")
file.close()
print("Please login now.")
time.sleep(1)
logged = True
login()
def login(): #This function has been adapted from www.stackoverflow.com
print("Please enter your credentials.")
time.sleep(1)
login.username = str(input("Please enter your username: "))
password = str(input("Please enter your password: "))
for line in open("outputusernamefile.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 login.username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
print("You are now logged in.")
logged = True
QuizStart()
return True
else:
print("Incorrect credentials.")
print("Please try again.")
time.sleep(0.5)
login()
return False

You're quitting the loop in the very first iteration. That's why only one line is being checked. Perhaps try to do something like this.
def login():
...
with open("outputusernamefile.txt","r+") as file:
for line in file.readlines():
login_info = line.split() # Split on the space, and store the results in a list of two strings
if login.username == login_info[0] and password == login_info[1]:
print("Correct credentials!")
print("You are now logged in.")
logged = True
QuizStart()
return True
print("Incorrect credentials.")
print("Please try again.")
time.sleep(0.5)
login()

The recursive call in the login function starts reading the file from the beginning because the file is opened again.
You need to read the entire file, searching for a match, and then make the final decision at the end of the loop. You can only return early if the function finds the requested user name.

Here's how it works for me. You forgot to iterate over the lines one by one.
import time
def register(): #This function has been adapted from www.stackoverflow.com
print("Please register.")
time.sleep(1)
username = input("Please input your desired username: ")
file = open("outputusernamefile.txt","a")
file.write(username)
file.write(" ")
password = input("Please input your desired password: ")
file.write(password)
file.write("\n")
file.close()
print("Please login now.")
time.sleep(1)
logged = True
login()
def login(): #This function has been adapted from www.stackoverflow.com
print("Please enter your credentials.")
time.sleep(1)
login.username = str(input("Please enter your username: "))
password = str(input("Please enter your password: "))
with open("outputusernamefile.txt","r+") as file: # Read the lines
line = file.readline()
while line:
login_info = line.split() # Split on the space, and store the results in a list of two strings
if login.username == login_info[0] and password == login_info[1]:
user_found = True
print("QuizStart()")
return True
else:
time.sleep(0.5)
user_found = False
line = file.readline()
if not user_found:
print("Incorrect credentials.")
print("Please try again.")
login()
else:
print("Correct credentials!")
print("You are now logged in.")
register()

Related

Username search in file 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.")

Unable to compare input variable to data within a .txt / Unable to read file to compare data

Currently I'm in the process of making a program where you can both login and register and the username/password are stored in a separate .txt file.
Registering is working fine, the username and password is written without issue but I am having issues with reading from the file in both userRegister and userLogin
The .txt file is formatted by username,password and I was wondering how I would go about reading from the file with the intention of comparing loginUsername and loginPassword to username_password and comparing registerUsername to existing usernames to ensure there are no duplicates.
username_password = open("savedCredentials.txt", "r+")
option = ()
def startMenu():
option = input("Do you want to [login] or [register] an account?:")
if option == 'login':
return userLogin()
elif option == 'register':
return userRegister()
else:
print("Invalid input, enter either [login] or [register]")
return startMenu()
def userRegister():
registerUsername = input("Enter a username: ")
if registerUsername in username_password:
print("This username is already in use")
userRegister()
else:
registerPassword = input ("Enter a password: ")
if len(registerPassword) < 5:
print("Your password needs to contain 5 or more characters")
registerPassword()
elif " " in registerPassword:
print("Your password cannot contain spaces")
else:
register = open("savedCredentials.txt", "a")
register.write(registerUsername)
register.write(",")
register.write(registerPassword)
register.write("\n")
print("Your username and password have been successfully registered")
def userLogin():
loginUsername = input("Enter your username: ")
if loginUsername in username_password:
loginPassword = input("Enter your password: ")
if loginPassword in username_password:
successfulLogin()
else:
print("This username isn't registered to an account, please try again")
return userLogin()
def successfulLogin():
print("You have been logged in")
username_password.close()
A few things:
You aren't calling any functions in your above code, so nothing will run as it stands.
You cannot iterate a Text wrapper, you can get around this by just reading your file by .read()
If you close() the file outside of your functions, you'll get an error that the file is closed, close the file within your function instead (whenever the user is done).
It appears once you go through the conditional if search, the .read() doesn't work anymore for the 2nd round. Don't quite know why (maybe someone else here can go into more detail), but the workaround is instead convert your file to a list, and search through that instead.
The below works, but it is a bit ugly (I have to go know, but wanted to post this real quick so you have at least a working example, and can build off of it).
username_password2=[]
with open("savedCredentials.txt", "r+") as file:
for lines in file:
a=lines.replace(',',' ')
b=a.split()
username_password2.append(b)
username_password = [x for y in username_password2 for x in y]
option = ()
def startMenu():
option = input("Do you want to [login] or [register] an account?:")
if option == 'login':
return userLogin()
elif option == 'register':
return userRegister()
else:
print("Invalid input, enter either [login] or [register]")
return startMenu()
def userRegister():
registerUsername = input("Enter a username: ")
if registerUsername in username_password:
print("This username is already in use")
userRegister()
else:
while True:
registerPassword = input ("Enter a password: ")
if len(registerPassword) < 5:
print("Your password needs to contain 5 or more characters")
elif " " in registerPassword:
print("Your password cannot contain spaces")
else:
register = open("savedCredentials.txt", "a")
register.write(registerUsername)
register.write(",")
register.write(registerPassword)
register.write("\n")
print("Your username and password have been successfully registered")
register.close()
break
def userLogin():
loginUsername = input("Enter your username: ")
if loginUsername in username_password:
loginPassword = input("Enter your password: ")
if loginPassword in username_password:
successfulLogin()
else:
print(username_password)
else:
print("This username isn't registered to an account, please try again")
return userLogin()
def successfulLogin():
print("You have been logged in")
startMenu()
You have to add the read function to your file opening.
replace the line username_password = open("savedCredentials.txt", "r+")
by
username_password = open("savedCredentials.txt", "r+").read()
then you have to remove the line username_password.close()
also, you need to call your startMenu function so add startMenu() at the bottom of your code.

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()

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()

Python loop ending but then ends but then repeats for no reason

I am making a program for the backend of a profiling system for my exam practice. I have the username and passwords stored in a .txt file. It says it is valid when I enter the password and goes to the next part of the program but then loops back and asks for the details again???
Here is my code where I think the problem is:
def Login(): #Login function
f = open('login.txt','r')
username = f.readline().strip()
password = f.readline().strip()
usernameLog = input('Please enter your username: ')
validuser = False
while validuser == False:
if usernameLog == username:
print('Username accepted')
time.sleep(1)
userpassLog = input('Please enter a password: ')
if userpassLog == password:
print('Successfully logged in')
time.sleep(0.5)
Options()
validuser = True
else:
print('Please enter a valid password')
validuser = False
else:
print('Invalid username please re-enter it.')
validuser = False
Login()
f.close()
First to answer your question: under your else condition for a wrong password (under print('Please enter a valid password')), you have a non-indented validuser = False. So what happens is that the validuser = True that you set a bit earlier when the password was good is replaced instantly by a validuser = False. Simply indenting that line to put it within your else condition fixes your code :)
Now, talking optimisation/best practice... In your code you are using both an infinite loop conditional on a variable which is an iterative approach, and a call to your function within your function which is a recursive approach, which is not in my opinion a really good choice... Or at least not for the same level of the loop!
If you wanted to go fully iterative, then you would simply need to replace your Login() towards the end by
usernameLog = input('Please enter your username: ')
Or, if you want to have both a recursive call and an iterative loop, you could loop only over the password:
def Login():
f = open('login.txt','r')
username = f.readline().strip()
password = f.readline().strip()
usernameLog = input('Please enter your username: ')
if usernameLog == username:
print('Username accepted')
time.sleep(1)
validpassword = False
while validpassword == False:
userpassLog = input('Please enter a password: ')
if userpassLog == password:
print('Successfully logged in')
time.sleep(0.5)
Options()
validpassword = True
else:
print('Please enter a valid password')
validpassword = False
else:
print('Invalid username please re-enter it.')
Login()
f.close()
To be honest, re-opening the same file every time you enter a wrong username seems a bit of a waste of time, so I'd recommend using the iterative-only version if that's good with your assignment...
breaking solved the issue:
while validuser == False:
if usernameLog == username:
print('Username accepted')
time.sleep(1)
userpassLog = input('Please enter a password: ')
if userpassLog == password:
validuser = True
print('Successfully logged in')
time.sleep(0.5)
Options()
break

Categories