My script can't recognise names inside the username file - python

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.

Related

I am writing some code for a login system in python and I can't seem to be able to have it read the email and password from a txt file

import hashlib
def signup():
email = input("Enter an email address: ")
pwd = input("Enter a password: ")
conf_pwd = input("Confirm your password: ")
if conf_pwd == pwd:
enc = conf_pwd.encode()
hash1 = hashlib.sha256(enc).hexdigest()
with open(r'D:\Python Programs\Login\database.txt', "a") as f:
f.write(email + "\n")
f.write(hash1 + "\n")
f.close()
print("You have registered successfully!")
else:
print("Password is not same as above! \nPlease try again")
signup()
def login():
email = input("Enter email: ")
pwd = input("Enter password: ")
auth = pwd.encode()
auth_hash = hashlib.sha256(auth).hexdigest()
with open(r'D:\Python Programs\Login\database.txt', "r") as f:
stored_email, stored_pwd = f.read().split("\n")
f.close()
if email == stored_email and auth_hash == stored_pwd:
print("Logged in Successfully!")
else:
print("Login failed! \nPlease try again")
login()
def welcome():
print("Welcome to the [Insert Game Name Here]")
HaveAccount = input("Have you made an account before? (Y/N): ")
if HaveAccount == ("Y"):
login()
elif HaveAccount == ("N"):
signup()
else:
print("Please enter either 'Y' or 'N'")
welcome()
welcome()
It is specifically line 23 and it has a ValueError: too many values to unpack (expected 2) whenever I try and log in with an email and password. I need to add some extra text in because my post is mostly code and I don't know what else to say so here is some random typing to make more characters in my post. Any help is appreciated. Thanks

Account creation program is not reading file properly

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.

Is there a reason why the program is not able to compare the users input and the file?

I cannot see a reason why my program isnt able to compare the users input and such. My program is a Username/Password program for a OS i am working on i am not sure why it isnt working it always fires back with incorrect even when it is correct?
import os
isuserempty = os.stat("Username.txt").st_size == 0
ispassempty = os.stat("Password.txt").st_size == 0
if isuserempty or ispassempty == True:
print("Hello, new user create a username and password.")
newusername = input("Enter your new username: ")
NewUser = open("Username.txt" , "a")
NewUser.write(newusername)
NewUser.close()
newpassword = input("Enter your new password: ")
NewPass = open("Password.txt" , "a")
NewPass.write(newpassword)
NewPass.close()
print("You now have a new Username and Password!")
print("You are now logged in!")
elif isuserempty or ispassempty == False:
truePass = open("Password.txt", "r")
trueUser = open("Username.txt", "r")
print("Enter your Username.")
userUserName = input("Enter:")
print("Enter your password.")
userPass = input("Enter:")
if userUserName == trueUser and userPass == truePass:
print("Correct! Logging in...")
if userUserName != trueUser or userPass != truePass:
print("Incorrect!")
Your truePass and trueUser are variables of type TextIOWrapper (files) which you currently compare to strings. In your elif block, read the contents of your files like this before doing the comparison.
pass_file = open("Password.txt", "r")
truePass=pass_file.read()
user_file = open("Username.txt", "r")
trueUser = user_file.read()

How do I create this loop? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
How do I create this loop where if welcome is not equal to "yes" or "no", it repeats the question (if they have an account), but if welcome is equal to "yes" or "no", they create an account (for "no") or allow the user to login (for "yes")?
Thanks in advance
Below is my code used :
welcome = input("Do you have an account? Please type either 'yes'/'no': ")
if welcome == "no":
while True:
username = input("OK. Let's create an account. Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open(username+".txt", "w")
file.write(username+":"+password)
file.close()
welcome = "yes"
break
print("Passwords do NOT match!")
if welcome == "yes":
while True:
login1 = input("OK. Enter your username:")
login2 = input("Enter your password:")
file = open(login1+".txt", "r")
data = file.readline()
file.close()
if data == login1+":"+login2:
print("You have successfully logged in as, " + login1)
print("")
print("Welcome to the Music Quiz!")
break
print("Incorrect username or password.")
Put a loop around asking for welcome.
while True:
welcome = input("Do you have an account? Please type either 'yes'/'no': ")
if welcome in ("yes", "no"):
break
if welcome == "no":
...
else:
...
You can add a bool variable that keeps track of user's input status (valid/invalid)
validAnswer = False:
while not validAnswer:
welcome = input("Do you have an account? Please type either 'yes'/'no': ")
if welcome == "no":
validAnswer = True
while True:
username = input("OK. Let's create an account. Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open(username+".txt", "w")
file.write(username+":"+password)
file.close()
welcome = "yes"
break
print("Passwords do NOT match!")
elif welcome == "yes":
validAnswer = True
while True:
login1 = input("OK. Enter your username:")
login2 = input("Enter your password:")
file = open(login1+".txt", "r")
data = file.readline()
file.close()
if data == login1+":"+login2:
print("You have successfully logged in as, " + login1)
print("")
print("Welcome to the Music Quiz!")
break
print("Incorrect username or password.")
You can simply add a while True: to the whole thing, this way, when a "wrong" input is entered, it will fall through both of the if clauses and return to the beginning of the loop, where it will prompt the user again.
while True:
welcome = input("Do you have an account? Please type either 'yes'/'no': ")
if welcome == "no":
while True:
username = input("OK. Let's create an account. Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open(username+".txt", "w")
file.write(username+":"+password)
file.close()
welcome = "yes"
break
print("Passwords do NOT match!")
if welcome == "yes":
while True:
login1 = input("OK. Enter your username:")
login2 = input("Enter your password:")
file = open(login1+".txt", "r")
data = file.readline()
file.close()
if data == login1+":"+login2:
print("You have successfully logged in as, " + login1)
print("")
print("Welcome to the Music Quiz!")
break
print("Incorrect username or password.")

How can i create a login with a text file

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

Categories

Resources