I've been making a program that allows the user to create an account which saves to a txt file, and allows them to login. The text now saves to the file (which I was unable to make work earlier due to using w+ instead of a+) but I am not quite sure I understand how split() works. When I try to use the info saved to the txt file the program returns that the username cannot be found. If anyone could fix this code id appreciate it.
I began a few weeks ago so a lot of this is new to me.
AccountsFile = open("AccountProj.txt", "a+")
AccountList = [line.split('\n') for line in AccountsFile.readlines()]
#Creates an account
def createaccount():
while True:
newname = (input("Please create a username: "))
if newname in AccountsFile:
print("Username already in use.")
continue
elif newname not in AccountsFile:
newpassword = input("Please create a password: ")
checkpassword = input("Re-enter password: ")
if checkpassword == newpassword:
print("Account Sucessesfuly created!")
AccountsFile.write(newname + '\n')
AccountsFile.write(checkpassword + '\n')
AccountsFile.close()
break
elif checkpassword != newpassword:
print("Passwords do not match")
continue
#Logs into an account
def loginaccount():
while True:
username_entry = input("Enter username: ")
if username_entry not in AccountList:
print("Username not found. Please enter a valid name")
continue
if username_entry in AccountList:
password_entry = input("Enter password: ")
if password_entry in AccountList[AccountList.index(username_entry) + 1]:
print("Login sucessful!")
AccountsFile.close()
break
if password_entry not in AccountList[AccountList.index(username_entry) + 1]:
print("Username and password do not match. Please try again.")
AccountsFile.close()
continue
while True:
#Asks if user wants to create or login to an account
loginchoice = input("Would you like to login? (Y/N) ")
if loginchoice in ('Y', 'N'):
if loginchoice == 'Y':
loginaccount()
if loginchoice == 'N':
createchoice = str(input("Would you like to create an account? (Y/N) "))
if createchoice in ('Y', 'N'):
if createchoice == 'Y':
createaccount()
if createchoice == 'N':
pass
break
else:
print("Invalid Input")
def CreateAccount():
Username = input("Username: ") #Enter Username
Username.replace(" ", "") #Removes spaces (Optional)
AppValid = True #Default value that changes if duplicate account found
File = open("Accounts.txt","r") #Checking if username already exits
for Line in File:
Account = Line.split(",")
if Account[0] == Application:
print("There is already an Account with this Username")
AppValid = False #Changing value if username exits
File.close()
if AppValid == True: #If username not found, carries on
Password = input("Password: ") #Asks for Password
CheckPassword = input("Password: ")
if Password == CheckPassword:
print("Password's Match!") #Password Match
else:
print("No match")
File = open("Accounts.txt","a") #Writing new account to File
File.write(Username + "," + Password + "\n")
File.close()
def ViewAccount(Username, Password):
File = open("Accounts.txt","r")
Data = File.readlines()
File.close()
if len(Data) == 0:
print("You have no Accounts") #Account not found since no accounts
else:
AccountFound = false
for X in Data: #Looping through account data
if X[0] == Username: #Username match
if X[1] == Password:
AccountFound = true
print("Account Found")
if AccountFound = false:
print("Account not FOUND")
Theres some code i threw together (JK my hand hurts from typing that and my keyboard is screaming) but back to the point .split(" ") would split a string into a list based on spaces for that example, eg:
String = "Hello There"
String = String.split(" ") #Or String.split() only owrks for spaces by default
print("Output:", String[0]) #Output: Hello
print("Output:", String[1]) #Output: There
String = "Word1, Word2"
String = String.split(", ") #Splits string by inserted value
print("Output:", String[0]) #Output: Word1
print("Output:", String[1]) #Output: Word2
String = "abcdefghijklmnop"
String = String.split("jk") #Splits string by inserted value
print("Output:", String[0]) #Output: abcdefghi
print("Output:", String[1]) #Output: lmnop
Check AccountList - both split() and readlines() create a list for you, so you have a list of lists and your username_entry check can't work that way.
Related
It can see the file, if i change the name on the path slightly run seizes to function but eithr way it can't read the words in the file despite being able to before while I was writing the program. And now suddenly it doesn't work, the file location is the same and all.
P.S. I have no idea how to specify code on overflow
filen = 'C:\Users\fabby\Documents\Extra Things I Might Need\Port Folio Stuff\Python\usernames'
usern = open(filen, 'r')
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
def func():
user = input("Enter new Username: ")
passs = input("Enter new Password: ")
passs1 = input("Confirm password: ")
if passs != passs1:
print("Passwords do not match!")
else:
if len(passs) <= 6:
print("Your password is too short, restart:")
elif user in usern:
print("This username already exists")
else:
usern = open(filen, "a")
usern.write(user+", "+passs+"\n")
print("Success!")
while True:
if userr not in usern:
again = input("This username does not exist, would you like to try again? ")
if again == ("No"):
func()
elif again == ("no"):
func()
elif again == ("Yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif again == ("yes"):
print("Try again:")
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")
elif userr in usern:
print("Good, you have entered the zone")
I am not sure I have full understand your means, but as your code, I have some suggestions:
close file if you open it
use f.readline() and str.split() to parse username and passwd and store in array, so you can use in to check, if the file is not to large.
The code is meant to be a simple login code that saves the login information to a .txt file and then when logging in reads the text file to check the user details.
The code runs up until I create an account or try to login and put in my username and password then it comes back with None. I don't understand why it's coming back with None
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
loginexisting()
elif account == "N":
createacc()
else:
print("please type Y or N")
AskAccount()
def loginexisting():
print("Your account already exists, please login\n")
username = input("Please enter your username:")
password = input("Please enter your password:")
f = open('accounts.txt', 'r')
info = f.read()
info = info.split()
if username in info:
index= info.index(username) +1
usr_password = info[index]
if usr_password == password:
return "Welcome Back," + username
else:
return "password entered is wrong"
else:
print("Username is not correct")
print(createacc())
def createacc():
print("Lets create an account for you\n")
username = input("Please input your username:\n")
password = input("please input your password\n")
f = open("accounts.txt",'r')
info = f.read()
if username in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("accounts.txt",'w')
info = info + " " + username + " " + password
f.write(info)
f.close()
print("Your account details have been saved\n")
print("please login\n")
print(AskAccount())
At the end of your file, you print(AskAccount()). This prints the return value of the function, but AskAccount does not have a return statement, thus it returns None. If you want it to print your desired output, you will need to add return statements.
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
return loginexisting()
elif account == "N":
return createacc()
else:
print("please type Y or N")
return AskAccount()
This question already has an answer here:
Searching array reports "not found" even though it's found
(1 answer)
Closed 1 year ago.
My code is always saying it is incrorrect even tough it is present on the text file,
it was working before but now isn't for some reason.
def select_login_signup():
while True:
selection = input("Welcome to sports.com, please select"
" \"L\" to Log In with your account or \"S\" to create an account: ")
if selection.lower() == 's':
register()
answer = input("Would you like to Log In? Y/N? ")
while not answer:
if answer.lower() == "y":
login()
break
elif answer.lower() == "n":
exit()
else:
answer = False
print("Invalid answer.")
continue
elif selection.lower() == 'l':
login()
break
else:
print("Invalid answer.")
continue
def register():
username = input("Create your username (no more than 10 characters or less than 4.): ")
while 10 < len(username) < 4:
print('username cannot have more than 10 characters or less than 4.')
username = input("Create your username (no more than 10 characters or less than 4.):
")
break
while username.isnumeric():
print("username must contain at least one letter")
username = input("Create your username (no more than 10 characters or less than 4.):
")
break
password = input("Create a password with letters and numbers: ")
while len(password) < 6:
print("Your password must contain more than 6 characters.")
password = input("Create a password with letters and numbers: ")
continue
while password.isnumeric() or password.isalpha():
print("Your password must contain both letters and numbers")
password = input("Create a password with letters and numbers: ")
continue
login_credentials = open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', "a")
login_credentials.write(f'\n{username},{password}')
login_credentials.close()
print("Account created successfully.")
def login() -> object:
username = input("Please enter your username: ")
username = username.strip()
password = input("Please enter your password: ")
password = password.strip()
login_credentials = open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', "r")
login_credentials.readlines()
with open('C:\\Users\\hmarq\\Documents\\UsernameAndPassword.txt', 'r') as
login_credentials:
for line in login_credentials:
login_info = line.split(",")
if username == login_info[0] and password == login_info[1]:
print("Authorized")
authenticated = True
return authenticated
else:
print("Incorrect credentials.")
username = input("Please enter your username: ")
username = username.strip()
password = input("Please enter your password: ")
password = password.strip()
continue
def main():
select_login_signup()
if __name__ == "__main__":
main()
with open('C:\Users\hmarq\Documents\UsernameAndPassword.txt', 'r') as login_credentials
when you open a file, you have to format the data and therefore the data is not the same.
if username == login_info[0] and password == login_info[1]:
I hope it serves you, greetings.
I made a program that allows the user to create an account. It seemed to work until I tried the login feature, which kept alerting me that the username and password do not exist. When I re-run the program and create an account, the txt file has my given name and password inside. However when I close the program and reopen it to run the login feature the name and password are no longer there. Any ideas on how to fix this?
PS: I'm rather new to all of this and if there is anything i could/should have done instead please let me know.
while True:
#Account file and same file as list.
AccountsFile = open("AccountProj.txt", "w+")
AccountList = [line.split(',') for line in AccountsFile.readlines()]
#Creates an account
def createaccount():
while True:
newname = (input("Please create a username: "))
if newname in AccountsFile:
print("Username already in use.")
continue
elif newname not in AccountsFile:
newpassword = input("Please create a password: ")
checkpassword = input("Re-enter password: ")
if checkpassword == newpassword:
print("Account Sucessesfuly created!")
AccountsFile.write(newname + "\n")
AccountsFile.write(checkpassword + "\n")
AccountsFile.close()
break
elif checkpassword != newpassword:
print("Passwords do not match")
continue
#Logs into an account
def loginaccount():
while True:
username_entry = input("Enter username: ")
if username_entry not in AccountList:
print("Username not found. Please enter a valid name")
continue
elif username_entry in AccountList:
password_entry = input("Enter password: ")
if password_entry in AccountList[AccountList.index(username_entry) + 1]:
print("Login sucessful!")
AccountsFile.close()
break
if password_entry not in AccountList[AccountList.index(username_entry) + 1]:
print("Username and password do not match. Please try again.")
AccountsFile.close()
continue
#Asks if user wants to create or login to an account
loginchoice = input("Would you like to login? (Y/N) ")
if loginchoice in ('Y', 'N'):
if loginchoice == 'Y':
loginaccount()
if loginchoice == 'N':
createchoice = str(input("Would you like to create an account? (Y/N) "))
if createchoice in ('Y', 'N'):
if createchoice == 'Y':
createaccount()
if createchoice == 'N':
exit()
break
else:
print("Invalid Input")
You opened your file in w+ mode, this will override your previous content because it starts writing right at the beginning of the file.
Instead, you should use the a mode for appending your text to any previously written content.
See: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files:
(...) mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end.
So I've been trying to create a quiz where you have to have an account which means you can register and login. I managed to code the register part(which i'm pretty proud of) and it saves the login details to a separate text file, when it saves the login details it looks like this: username:password
Now i'm struggling with the login part, I think you have to read the text file and then split the username and password, then I some how have to compare the inputted username and password to the saved ones.
This is what I done for the login part so far but it doesn't work:
def login():
filename = 'Accounts.txt'
openfile = open('Accounts.txt', "r")
Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
for line in file:
user2, passw = line.split(':')
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
if login2 == user2 and passw2 == passw:
print("Logged in")
else:
print("User or password is incorrect!")
openfile.close();
Now this is how the whole code looks like(if needed):
import time
print("Welcome to my quiz")
#Creating username
def create():
print ("We will need some information from you!")
time.sleep(1)
Veri = input("Would you like to continue (yes or no): ")
def createAccount():
while True:
name = input("Enter your first name: ")
if not name.isalpha():
print("Only letters are allowed!")
else:
break
while True:
surname = input("Enter your surname: ")
if not surname.isalpha():
print("Only letters are allowed!")
else:
break
while True:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Only numbers are allowed!")
continue
else:
break
if len(name) >= 3:
username = name[0:3]+str(age)
elif len(surname) >= 3:
username = surname[0:3]+str(age)
else:
username = input("Create a username: ")
print ("Your username is:",username)
while True:
password = input("Create a password: ")
password2 = input("Confirm your password: ")
if password != password2:
print("Password does not match!")
else:
break
account = '%s:%s\n'%(username,password)
with open ('Accounts.txt','a') as file:
file.write(account)
print ('Account saved')
if Veri == 'no':
menu()
elif Veri == 'yes':
createAccount()
else:
print ("Sorry, that was an invalid command!")
time.sleep(1)
login()
#Loging in
def login():
filename = 'Accounts.txt'
openfile = open('Accounts.txt', "r")
Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
for line in file:
user2, passw = line.split(':')
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
if login2 == user2 and passw2 == passw:
print("Logged in")
else:
print("User or password is incorrect!")
openfile.close();
time.sleep(1)
#Choosing to log in or register
def menu():
LogOrCre = input("Select '1' to login or '2' to register: ")
if LogOrCre == '1':
login()
elif LogOrCre == '2':
create()
else:
print ("Sorry, that was an invalid command!")
menu()
menu()
If you have any ideas on how I can make the login part, that would be helpful.
You are asking for the user's username and password for every line in the accounts file. Get the inputted login information outside of the for loop.
Welcome to programming!
It can be very daunting, but keep studying and practicing. You are in the right way!
I see some points in your code that could be improved. I'm commenting below:
1) You don't need to use both open() (and close()) and with to access a file's contents. Just use with, in this case. It will make you code simpler. (A good answer about with)
2) You're asking for the user login & passwd inside a loop (aka multiple times). It can be very annoying for your user. Move the input's call to before the for loop.
3) You also need to break the loop when the login succeeds.
So, a slightly improved version of your code would be:
filename = 'Accounts.txt'
with open(filename, 'r') as file:
login2 = input("Enter username: ")
passw2 = input("Enter password: ")
for line in file:
user2, passw = line.split(':')
if login2 == user2 and passw2 == passw:
print("Logged in")
break
else:
print("User or password is incorrect!")
Not sure what is not working in your code, but I updated the code as below and was able to print logged in.
def login():
#filename = 'Accounts.txt'
#openfile = open('Accounts.txt', "r")
#Userdata = openfile.readlines()
with open('Accounts.txt', 'r') as file:
login2 = input("Enter username: ")
passw2 = input("Enter passwordd: ")
for line in file:
user2, passw = line.split(':')
if login2 == user2 and passw2 == passw:
print("Logged in")
break
else:
continue
login()