i am having trouble with open() command in python - python

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

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

Program keeps displaying None even after input

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

Text file clearing itself when program is run again

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.

write on new line in csv

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.

Python Pickled Passwords

This is my python password system using pickle. It's bad, I know, but it's my first time with pickle.
import pickle
import os
userlist = {'user1':'userpass1', 'user2':'userpass2'}
users = open ("users.pkl", 'wb')
pickle.dump (userlist, users)
username = input ("Enter your username: ")
password = input ("Enter your password: ")
if (username in userlist) and (password == userlist[username]):
print ("Access Granted")
else:
newaccount = input ("User not found. Shall I create a new account? ")
if newaccount == "yes":
username = input ("Please enter your username: ")
password = input ("Please enter yout password: ")
userlist.update({username:password})
pickle.dump (userlist, users)
users.close()
My problem is that, whenever I go to add a new account, using this part:
newaccount = input ("User not found. Shall I create a new account? ")
if newaccount == "yes":
username = input ("Please enter your username: ")
password = input ("Please enter yout password: ")
userlist.update({username:password})
pickle.dump (userlist, users)
users.close()
It seems to add it (and it looks like it's there in the pickle file using notepad) but, I restart the python file, and it does not see it.
I believe it is something to do with this part:
userlist = {'user1':'userpass1', 'user2':'userpass2'}
users = open ("users.pkl", 'wb')
pickle.dump (userlist, users)
Any help is appreciated! :D
You overwrite each time you run the program with w:
users = open ("users.pkl", 'wb')
If you wanted to get the previously pickled items you would need to see if the file already exists and pickle.load to get the previously pickled items and then dump at the end of your code.
Something like the following:
from tempfile import NamedTemporaryFile
try:
# see if we have run this before
with open ("users.pkl", 'rb') as users:
users_dict = pickle.load(users)
except IOError:
# if not set to defualt
users_dict = {'user1':'userpass1', 'user2':'userpass2'}
username = input ("Enter your username: ")
password = input ("Enter your password: ")
if users_dict.get(username) == password: # unless a password can be None we can use get
print ("Access Granted")
else:
newaccount = input("User not found. Shall I create a new account? ")
if newaccount == "yes":
username = input("Please enter your username: ")
password = input ("Please enter yout password: ")
users_dict[username] = password # just use key = value
with NamedTemporaryFile("wb",dir=os.path.dirname("users.pkl"),delete=False) as f: # in case we get exception use temp file
pickle.dump (users_dict, f)
os.replace(f.name,"users.pkl") # update original

Categories

Resources