I have a code that writes usernames, passwords and scores into a csv file in the format: username, password, score. I have it so it writes the username and password at the beginning of the code:
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
login=open("login.csv","a")
login.write(username + "," + password + "\n")
login.close()
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
I do this for user one and user 2.
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
In the code, this puts the usernames and passwords into column 0 and 1.
Then at the end after the game, it writes the score into the csv file. The part i'm struggling with is then writing the score into column 2. I need it to write on the next available cell in the csv file in row 2.
Any help on this would be greatly appreciated.
Dylan
If I correctly interpreted your request, you simply have to modify this line:
login.write(username + "," + password + "\n")
with
login.write(username + "," + password + ",")
and then add the score with the line terminator '\n'.
In this way you'll get:
username,password,score
all in the same line.
I rewrote your code, so it's readable:
def login_system():
loggedin = False
with open("login.csv", newline='') as fid:
reader = csv.reader(fid, delimiter=",")
login = list(reader)
while not loggedin:
ans=input("Do you have an account? (yes/no) ")
if ans.lower()=="yes":
username=input("What is your username: ")
password=input("What is your password: ")
if [username, password] in login:
print("Welcome " + username)
loggedin=True
return loggedin
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif ans.lower() == "no":
username=input("New username: ")
password=input("New password: ")
with open("login.csv", "a") as login:
login.write(username+","+password+"\n")
print("Welcome "+username)
loggedin = True
return loggedin
don't give two variables the same name
use the with statement for file handling
don't open and close the same file hundreds of times, when you only need to do so once
Lastly to your actual question:
It's way easier just writing a new file or overwriting the old one. And also faster.
Related
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
I am currently developing a desktop login-register app for my practice, and was having some trouble with login and register. If I type REGISTER and add my info in f.write() command it stores my info but after that everything just goes, like the whole file gets formatted (this was register issue).
The login issue is if I want to check whether a name or password in file exists or not (this command could be wrong). I tried to use if login_email and login password in f: but it says that login_email and password do not exist.
Code:
f = open('pass.txt', 'w')
fr = open('pass.txt', 'r')
from time import sleep
login_list = "LOGIN"
register_list = "REGISTER"
if 1 > -3232:
print("Type register for new account\ntype login for login into existing account")
bi = input("==> ")
if bi.upper() in login_list:
print("you are registered?? nice now loginnn!!")
login_1 = input("your username: ")
login_2 = input("your password: ")
if login_1 and login_2 in fr:
print("Nice my program worked??")
exit()
else:
exit()
elif bi.upper() in register_list:
print("you are in register section: ")
sleep(.9)
print("NOTE: Your password should only contain alphabets!")
sleep(4)
reg_1 = input("your username: ")
sleep(.9)
reg_2 = input("your password: ")
sleep(.9)
reg_2v1 = input("confirm password")
if reg_2 == reg_2v1:
f.write(reg_1 + " : " + reg_2 + "\n")
print("now login again,\")
else:
print("invalid password, try again")
else:
print("you gave me the wrong command")
else:
exit()
You shouldn't open the file in both read and write mode at the beginning of the script. Opening it in write mode empties the file, so you won't be able to read it. You'll also wipe out all the other usernames and passwords. You should open the file in read mode when logging in, and append mode when registering, to add a new line without removing the old ones. And you should use with to just open the file around the code that needs to use it.
if login_1 and login_2 in fr: is not the correct way to test if both the username and password are in the file. Due to operator precedence, that's parsed as if login_1 and (login_2 in fr):. This just checks that login_1 is not empty, and then just checks if login_2 is in the file. The second test will never work, because the lines of the file all end with newline, but login_2 doesn't, so they'll never match.
You need to check for the fully formatted line, including the newline.
if f'{login_1} : {login_2}\n' in fr:
if bi.upper() in login_list: seems suspicious. login_list is not a list, it's a string. So this will check whether bi.upper() is any substring -- it will succeed if the user enters log or in or gi, not just login. Is that intentional?
Full code:
from time import sleep
login_list = "LOGIN"
register_list = "REGISTER"
if 1 > -3232:
print("Type register for new account\ntype login for login into existing account")
bi = input("==> ")
if bi.upper() in login_list:
print("you are registered?? nice now loginnn!!")
login_1 = input("your username: ")
login_2 = input("your password: ")
with open('pass.txt', 'r') as fr:
if f'{login_1} : {login_2}\n' in fr:
print("Nice my program worked??")
exit()
else:
exit()
elif bi.upper() in register_list:
print("you are in register section: ")
sleep(.9)
print("NOTE: Your password should only contain alphabets!")
sleep(4)
reg_1 = input("your username: ")
sleep(.9)
reg_2 = input("your password: ")
sleep(.9)
reg_2v1 = input("confirm password")
if reg_2 == reg_2v1:
with open('pass.txt', 'a') as f:
f.write(reg_1 + " : " + reg_2 + "\n")
print("now login again,")
else:
print("invalid password, try again")
else:
print("you gave me the wrong command")
else:
exit()
I have a log in system for two users. I had duplicate code for it but I made it a function to make the code more efficient. However, I am not too sure how to make some variables change for each user. Here is the code:
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
Basically, I want to have username and password different for user 1 to user 2 but I have no idea where to start and nothing seems to help. When I input the username and password for user two, it overwrites the input I made for user one and I don't want that happening. Thanks,
Dylan
It seems you are practicing python or a simple question, well I have added the Pseudo code which you can develop yourself because it is simple and if you write this yourself it will help you think in that paradigm inorder to solve this problem.
Whenever you want to do something or implement it, do it in steps or write it down, it helps alot.
Read this btw.
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
#How to Save Username and password
#1. Find Two Empty Rows or one empty row and it's corresponding column in CSV file. (Can be done using running a loop on the csv file)
#2. Store Username password in the corresponding rows and columns above.
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
As per your requirements it seems that dictionary of successfully logged in usernames and passwords could be better for you if you store them
Make your code as belows.
users_logged_in={}
def login_system():
loggedin = False
while not loggedin:
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login=open("login.csv")
reader = csv.reader(login)
username=input("What is your username: ")
password=input("What is your password: ")
for row in reader:
if row[0]==username and row[1]==password:
print("Welcome " + username)
# usernames and passwords you have entered stored in dict
users_logged_in[username]=password
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
elif login.lower()=="no":
print(" ")
print("Make an account.")
print(" ")
username=input("What is your username: ")
password=input("What is your password: ")
break
else:
print("Invalid input.")
continue
print("User 1:")
login_system()
print("")
print("User 2:")
login_system()
If you want the order of the usernames logged in to system to be preserved go to OrderedDict from Python collections.
Else you could create list with tuples of usernames and passwords
Create tuple as below in above code
logged_user_details=(username,passowrd)
and let
users_logged_in
be a list of usernames and passwords, Append to it the tuple created above.
users_logged_in.append(logged_user_details).
Now you would have users and passwords in your list as shown below and order of your entry will also be preserved.
[(User1,Password1),(User2,Password2),(User3,Password3)].
It is entirely dependent on your usage purpose of storing username and password whether you go with List or Dict approach.
The login system i have wont break out of the loop. I have shown this to my CS teacher and he told me to change the indentations of the break. It didn't work. I have been looking around but I can't seem to find a reason as of why the loop wont break. Here is the code:
while True:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1:
if row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
The code asks if the user has an account. When I input yes and give valid username and password, it continues with the loop. For context when the user logins in, it says welcome and breaks out of the loop. However this isn't happening, it is instead saying welcome and restarting the loop. The csv for this contains the login details.
Any help as of why the loop wont break will be greatly appreciated.
Dylan
Something like this? I mean you already have a "loggedin" variable, why not use it in the while loop...
loggedin = False
while not loggedin:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1 and row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
You are missing a break.
You break out of the for loop, but never the while loop.
Try this:
while True:
print("User 1")
login=input("Do you have an account? (yes/no) ")
loggedin=False
if login.lower()=="yes":
login1=open("login.csv")
reader = csv.reader(login1)
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1:
if row[1]==password1:
print("Welcome " + username1)
loggedin=True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
continue
if loggedin==True:
break
EDIT:
Personally, i would avoid using a while True and instead do something like this:
loggedin = False
while not loggedin:
print("User 1") # Consider moving this outside of the while loop too
login=input("Do you have an account? (yes/no) ")
if login.lower() == "yes":
login1=open("login.csv") # Consider moving this outside of the while loop too
reader = csv.reader(login1) # Consider moving this outside of the while loop too
username1=input("What is your username: ")
password1=input("What is your password: ")
for row in reader:
if row[0]==username1 and row[1]==password1:
print("Welcome " + username1)
loggedin = True
break
if loggedin==False:
print("Invalid username or password. Please try again.")
Note here that the continue is not needed.
I need to check that the usernames and passwords match up with the details in a text file. I'm not sure how to do this. Here is what i have so far (saving the username to the file).
print("Are you a returning player?")
user = input()
if user.lower() == "no":
username = input("Please enter a username for your account.\n")
password = input("Please enter a password for your account.\n")
file = open("account.txt","a")
file.write(username)
file.write("\n")
file.write(password)
file.close()
else:
user_name = input("Please enter your username.\n")
pass_word = input("Please enter your password.\n")
There is another method using with open that close your file after the procedures are done inside the loop, so you can create a read loop and an append loop. For this I like the idea of storing the name and password on the same line, that way we can check to make sure the name and corresponding password are linked to each other rather than being able to use any password for any name. Also when using append we are going to have to add a '\n' or everything we write will be written to the same line
To verify the user we open the file as r and then we can use for line in f to get all the lines in the .txt from there we can loop through each line and if both username and password exist in the same line, we can welcome the user, if not send them back to the beginning.
Hope this helps!
while True:
user = input('\nAre you a returning player: ')
if user.lower() == 'no':
with open('accounts.txt', 'a') as f:
username = input('\nEnter username: ')
password = input('Enter password: ')
combo = username + ' ' + password
f.write(combo + '\n')
else:
with open('accounts.txt', 'r') as f:
username = input('\nEnter username: ')
password = input('Enter password: ')
for line in f:
if username + ' ' + password + '\n' == line:
print('Welcome')
break
else:
print('Username and/or Password Incorrect')
Are you a returning player: no
Enter username: vash
Enter password: stampede
Are you a returning player: yes
Enter username: vash
Enter password: stacko
Username and/or Password Incorrect
Are you a returning player: yes
Enter username: vash
Enter password: stampede
Welcome