I'm trying to create an encryption program that is also capable of using a username and password to be accessed, alongside the password being able to be changed, however, I am getting the following error when trying to read the password from a file.
Traceback (most recent call last):
File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 28, in <module>
password()
File "C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/a.py", line 9, in password
var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'Users\\Matthew\\AppData\\Local\\Programs\\Python\\Python37-32\\password.txt'
Password is saved in the Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt directory.
Below is the code.
import os
import time
def password():
while True:
username = input ("Enter Username: ")
password = input ("Enter Password: ")
var1 = "admin"
var2 = open("Users\Matthew\AppData\Local\Programs\Python\Python37-32\password.txt","r")
if username == var1 and password == var2:
time.sleep(1)
print ("Login successful!")
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
var2 = input("Enter new password: ")
elif input == "N" or "n":
break
logged()
break
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to the encryption program.")
password()
def main():
result = 'Your message is: '
message = ''
choice = 'none'
while choice != '-1':
choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
if choice == '1':
message = input("\nEnter the message to encrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print (result + '\n\n')
result = ''
elif choice == '2':
message = input("\nEnter the message to decrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print (result + '\n\n')
result = ''
elif choice != '-1':
print ("You have entered an invalid choice. Please try again.\n\n")
elif choice == '-1':
exit()
main()
Any help is appreciated, thanks!
Provide the complete path:
var2 = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python37-32/password.txt","r")
Edit:
As you said in the comment that it worked but the password was marked as incorrect, so I have fixed issues with your code.
You cannot read data directly by opening a file. You will have to use the command read to get the data:
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()
Your second code problem is setting new password. The code you made:
answer = input("Do you wish to change your password (Y/N): ")
if input == "Y" or "y":
var2 = input("Enter new password: ")
elif input == "N" or "n":
break
Don't use input to see the value, use the variable in which you stored the input data. Also lower the string to make it easy:
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
var2 = input("Enter new password: ")
elif answer.lower() == "n":
break
The full code can be like:
import os
import time
def password():
while True:
username = input ("Enter Username: ")
password = input ("Enter Password: ")
var1 = "admin"
file = open("C:/Users/Matthew/AppData/Local/Programs/Python/Python36/password.txt","r")
var2 = file.read()
file.close()
if username == var1 and password == var2:
time.sleep(1)
print ("Login successful!")
answer = input("Do you wish to change your password (Y/N): ")
if answer.lower() == "y":
var2 = input("Enter new password: ")
elif answer.lower() == "n":
break
logged()
break
else:
print ("Incorrect Information!")
def logged():
time.sleep(1)
print ("Welcome to the Encryption program.")
password()
def main():
result = 'Your message is: '
message = ''
choice = 'none'
while choice != '-1':
choice = input("\nDo you want to encrypt or decrypt the message?\nEnter 1 to Encrypt, 2 to Decrypt, -1 to Exit Program: ")
if choice == '1':
message = input("\nEnter the message to encrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print (result + '\n\n')
result = ''
elif choice == '2':
message = input("\nEnter the message to decrypt: ")
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print (result + '\n\n')
result = ''
elif choice != '-1':
print ("You have entered an invalid choice. Please try again.\n\n")
elif choice == '-1':
exit()
main()
Related
I'm a total newbie to programming and have just begun my first project which is a simple login app.
So far my code looks like this:
def login_or_registration():
user_choice = input("Login (L) or Registration (R)? ").lower()
if user_choice == "l":
print("You will be redirected to the login window.")
login()
elif user_choice == "r":
print("You will be redirected to the registration window.")
registration()
else:
print("Invalid choice.")
def registration():
name = input("Name: ")
surname = input("Surname: ")
username = input("Username: ")
pass1 = input("Password: ")
pass2 = input("Repeat password: ")
if pass1 != pass2:
print("Passwords don't match!")
email = input("E-mail: ")
age = input("Age: ")
while True:
if not age.isdecimal():
print("Please enter a number.")
if not name.isalpha():
print("Please use only letters for Name and Surname.")
if not surname.isalpha():
print("Please use only letters for Name and Surname.")
break
with open("userbase.txt", "a") as f:
f.write(username + "\n" + pass1 + "\n" + surname + "\n" + name + "\n" + email + "\n" + age + "\n" + "\n")
f.close()
user_choice = input("Would you like to log in now? (Y/N) ").lower()
if user_choice == "y":
login()
else:
"Quitting."
def login():
logged_in = False
username = input("USERNAME: ")
password = input("PASSWORD: ")
while logged_in == False:
f = open("userbase.txt", "r")
for line in f:
if line == username:
logged_in = True
print("Logged in!")
print("User not found!")
login_or_registration()
I know its incomplete and messy but for now i want to work on a function for logging in. My idea was to create a function that would iterate over a text file and search for a match to the users input I know it's not perfect and could have many problems but for now I want to avoid modules. I wrote the function login() but it doesn't work and I don't have an idea how to make it run. My idea was to make an if statement that would be checked for every iteration of a for loop inside a while loop combined with a boolean that would be set to True after the statement is true.
When I log in as an "existing user", it works perfectly when I log in first try
But in the while loop, when I get the login incorrect and it prompts me again and THEN I get the login correct, it comes up as login failed
import sys
existing = " "
possibleAnswersExisting = ["y","n"]
accountFileW = open("AccountFile.txt","a")
accountFileR = open("AccountFile.txt","r")
while existing not in possibleAnswersExisting:
existing = input("Are you an already existing user? (Please input y/n)\n>>")
if existing not in possibleAnswersExisting:
print('Please enter a valid answer. (Only "y" or "n")')
def register():
username = input("What would you like your username to be?")
password = input("What would you like your password to be?")
print("Welcome" ,username + "! Make sure to remember your password or write it down in case your forget!")
accountFileW.writelines([username, " ", password, "\n"])
def login():
x = ""
attempts = 0
while x != True:
lusername = input("What is your username? (CaSe SeNsItIvE PleAsE)\n>>")
lpassword = input("What is your password? (CaSe SeNsItIvE PleAsE)\n>>")
for line in accountFileR:
print("in for loop")
loginInfo = line.split()
print(loginInfo)
if lusername == loginInfo[0] and lpassword == loginInfo[1]:
print("--Successful login, setting x to true")
x = True
break
attempts = attempts + 1
if str((4 - attempts)) == 0:
print("Error, login credentials invalid. Exiting program...")
sys.exit()
if attempts > 0 and attempts < 5:
print("Incorrect" ,str((4 - attempts)), "attemptsleft.")
print("Successful login")
if existing == "n":
register()
elif existing == "y":
login()
else:
print("Error with existing")
sys.exit()
accountFileW.close()
accountFileR.close()
I expect the output for the login to be successful, but it says incorrect unlike when I get it right the first try
After Python has read a file, its "Prompt" is at the end of the file. If you do call read on the fileobject again it will return nothin since there is nothing left to read.
With seek(x) you can place the "Prompt" to the postion x. In you case 0 since you want to read the file again.
I injected the line on the right place:
import sys
existing = " "
possibleAnswersExisting = ["y","n"]
accountFileW = open("AccountFile.txt","a")
accountFileR = open("AccountFile.txt","r")
while existing not in possibleAnswersExisting:
existing = input("Are you an already existing user? (Please input y/n)\n>>")
if existing not in possibleAnswersExisting:
print('Please enter a valid answer. (Only "y" or "n")')
def register():
username = input("What would you like your username to be?")
password = input("What would you like your password to be?")
print("Welcome" ,username + "! Make sure to remember your password or write it down in case your forget!")
accountFileW.writelines([username, " ", password, "\n"])
def login():
x = ""
attempts = 0
while x != True:
lusername = input("What is your username? (CaSe SeNsItIvE PleAsE)\n>>")
lpassword = input("What is your password? (CaSe SeNsItIvE PleAsE)\n>>")
accountFileR.seek(0) # <---- injected line
for line in accountFileR:
print("in for loop")
loginInfo = line.split()
print(loginInfo)
if lusername == loginInfo[0] and lpassword == loginInfo[1]:
print("--Successful login, setting x to true")
x = True
break
attempts = attempts + 1
if str((4 - attempts)) == 0:
print("Error, login credentials invalid. Exiting program...")
sys.exit()
if attempts > 0 and attempts < 5:
print("Incorrect" ,str((4 - attempts)), "attemptsleft.")
print("Successful login")
if existing == "n":
register()
elif existing == "y":
login()
else:
print("Error with existing")
sys.exit()
accountFileW.close()
accountFileR.close()
import sys
def intro():
print("description of quiz")
choice1 = input("press A to login and B to signup ")
choice1.lower()
if choice1 == "b":
signup()
elif choice1 == "a":
login()
else:
print("Error, invalid input")
intro()
def signup():
name = input("name ")
age = input ("age ")
year = input ("year ")
username = name[:3] + age
print("Your username is " + username + " ")
password = str(input("desired password "))
userinfo = open("userinfo.txt","a")
userinfo.write(username + "," + password + "," + name + "," + age + "," + year + "\n")
userinfo.close()
quiztype()
def login():
username1 = input("Please input your username ")
userinfo = open("userinfo.txt","r")
userinforec = userinfo.readline()
while userinforec != "":
field = userinforec.split(",")
username = field[0]
password = field[1]
name = field[2]
age = field[3]
year = field[4]
if username == username1:
password1 = str(input("What is your password? "))
if password == password1:
print("password accepted")
quiztype()
else:
print("Error, password not accepted")
login()
userinforec = userinfo.readline()#ooooooooooooooooooooooooCOME BACK TO DO THE ELSE ERROR IF USERNAMES NOT EQUALooooooooooooooooooooooooooo
userinfo.close()
def quiztype():
quiztype = input("Choose maths or history? ")
quiztype.lower()
if quiztype == "maths":
print("You have chosen maths")
difficulty()
elif quiztype == "history":
print("You have chosen history")
difficulty()
else:
print("Error, invalid input")
quiztype()
return quiztype
def difficulty():
diff = input("Choose easy, medium, or hard ")
diff.lower()
if diff == "easy":
print("You have chosen easy")
elif diff == "medium":
print("You have chosen medium")
elif diff == "hard":
print("You have chosen hard")
else:
print("Invalid input")
difficulty()
return diff
def typeoffile():
if quiztype() == "maths":
topicfile = "maths.txt"
else:
topicfile = "history.txt"
return topicfile
def questionstolist():
questionfile = open(typeoffile(),"r")
qrec = questionfile.readline()
for line in qrec:
question, rightanswer, wrong1, wrong2, wrong3, wrong4 = line.strip().split(",")#problem is here
print(question)#^problem is here^
In the function, questionstolist(), I run the code and it comes up with the following error: ValueError:need more than 1 value to unpack.
I have read up on this error and I have rectified what I thought was the error however it did not work. In my file there are 6 sections separated by commas (5+5,10,11,17,5,12) and there are 6 variables that need to be assigned.
I am trying to make a login program that compares a user's input credentials to the credentials stored in a text file.
How do I do this correctly?
This is what I have done so far:
file = open("logindata.txt", "r")
data_list = file.readlines()
file.close()
print(data_list)
for i in range(0, len(data_list)):
username = input("username: ")
password = input("password: ")
i += 1
if i % 2 == 0:
if data_list[i] == username and data_list[i + 1] == password:
print("You are successfully logged in as", username)
i == len(data_list)
elif data_list[i] == username and data_list[i + 1] != password:
print("The password you entered was incorrect, please try again.")
else: # how do i end the code if the user inputs no
if data_list[i] != username:
choice = input("The username you entered was not found, would you like to create an account? (Y/N)")
if choice.upper() == "Y":
new_username = input("new username: ")
data_list.append(new_username + "\n")
new_password = input("new password: ")
data_list.append(new_password + "\n")
file = open("logindata.txt", "w")
file.writelines(data_list)
i == data_list
This is how the credential text file is set up:
user1
pass1
user2
pass2
I think you want something like this:
def does_username_exists(username, login_file_path):
username_exists = False
user_password = None
with open(login_file_path) as login_file:
while True:
username_line = login_file.readline()
if not username_line: break
password_line = login_file.readline()
if not password_line: break
if username == username_line.strip():
username_exists = True
user_password = password_line.strip()
break
return username_exists, user_password
def main():
login_file_path = "logindata.txt"
username = input("Enter username: ")
username_exists, user_password = does_username_exists(username, login_file_path)
if not username_exists:
choice = input("The username you entered was not found, would you like to create an account? (Y/N)")
if choice.upper() == 'Y':
new_username = input("Enter new username: ")
new_password = input("Enter new password: ")
with open(login_file_path, "a") as login_file:
login_file.write(new_username + "\n")
login_file.write(new_password + "\n")
return
password = input("Enter password: ")
if not (password == user_password):
print("The password you entered was incorrect, please try again.")
else:
print("You are successfully logged in as - '{}'".format(username))
if __name__ == "__main__":
main()
I am sorry but i have a problem that i dont understand...
def login_screen():
print(30 * "-")
print(" LOGIN")
print(30 * "-")
username = print("Please enter your username: ")
password = print("Please enter your password: ")
with open('logins.txt', 'r') as csvfile:
loginreader = csv.reader(csvfile, delimiter=',', quotechar= None)
for codes in loginreader:
if len(codes) == L_LEN:
if codes[L_USERNAME] == username and codes[L_PASSWORD] == password and codes[L_ADMIN] == "Yes":
admin_console()
elif username == row[L_USERNAME] and password == row[PASSWORD] and row[L_ADMIN] == "No":
#Temp normal console here
else:
clearscreen()
error_head()
print("Unknown account")
input("Press [ENTER] To continue...")
login_screen()
elif len(codes) != M_LEN:
next(csvfile, None)
So the problem is that it comes with the following error:
File "G:\Python\DatabaseStandardRewrite\Login.py", line 49
else:
^
IndentationError: expected an indented block
But i dont get it! (Yes, all the other things are defined in the rest of the document!
Does anyone of you see my mistake?
Natan
Python does not permit blocks to be empty; you need at least one statement, and a comment does not count. So in the elif block before your else, you should put pass.
elif username == row[L_USERNAME] and password == row[PASSWORD] and row[L_ADMIN] == "No":
#Temp normal console here
pass
else:
clearscreen()