How to I make it so in the code below when you register a username and password it it adds a new line to the txt files and when you login it checks every line in the txt files sepretly
and declaring it as correct if any of the lines match the login instead of it checking if the username and password matches the whole thing
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for
register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","w")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","w")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
if usr == file.read():
print "Username correct"
file.close()
else:
print "Username incorrect or not registered"
file.close()
file = open("Password.txt","r")
if pss == file.read():
print "Password correct"
file.close()
else:
print "Password incorrect or not registered"
file.close()
Here is how to find whether a string exists in some line of a file:
contain = False # Indicator of whether some line of a file contains the string
with open(FILENAME, 'r') as file: # Use `with` statement to automatically close file object
for line in file:
if string in line:
contain = True
break
I have modified your code to validate password and username with a password check logic. This should work.
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","a")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","a")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
count = 0
userfound = False
try:
for user in file.readlines():
count += 1
if usr == user.strip():
userfound = True
file.close()
if not userfound:
raise
file = open("Password.txt","r")
passcount = 0
for passcode in file.readlines():
passcount += 1
if count == passcount:
if pss == passcode.strip():
print 'successfully logged in'
else:
print "Password incorrect or not registered"
break
file.close()
except Exception as e:
print 'User login error !!!'
If you just want to check if the user is in the file contents,
if usr in file.read():
do_somethin
"==" checks if the value are same as it is, "in" keyword checks if the substring is in the huge string. In file.read() will have the whole contents as a string.
Related
I am completely new to programming and started a few days ago with learning Python(v.3.8.8). I wanted to make a small password manager, but with a little secret function(I think that's not important and it would take too much time to describe). Anyways I converted the main.py to a .exe with auto-py-to-exe but every time I wanna execute the .exe I can only enter my Login data and the window instantly closes but in Pycharm everything works totally fine. Does anyone know why?
EDIT: It works now, there was no missing "Input()" or stuff like that, I had a spelling mistake in my code and pycharm ignored it!
from cryptography.fernet import Fernet
welcome = input("Login(1), New User (2): ")
def new_user(): # creates a new user and safe the Username and pw in a .txt
print("The login is just for the safety of your data, everything is stored on your local PC!")
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
key = Fernet.generate_key()
f = Fernet(key)
f.encypt(b'password')
file = open(username + ".txt", "w")
file.write(username + ":" + password)
#file.close()
login() # go to login after everything is safed in the .txt
else:
print("Passwords do NOT match!")
def login(): # checks if the entered username and pw match with the .txt content
login1 = input("Login:")
login2 = input("Password:")
file = open(login1 + ".txt", "r")
pw = file.readline()
#file.close()
if pw == login1 + ":" + login2: # infinte trys to enter the username and pw
print("Welcome " + login1)
pwrequest()
else: # returns to login() if the pw is incorrect
print("Incorrect username or password. Please try again")
login()
def pwrequest():
q = input("safe new Password(1), show safed passwords(2)")
if q == "2":
data() # show all saved pw
if q == "1":
newdata() # go to data() if the user want to add a new pw or
# want to acces the hidden part
def data():
file = open('1.txt', 'r') # prints all saved passwords
file_pw = file.read()
print(file_pw)
file.close()
c = input("Press (1) to delete something and press (2) to log out.")
if c == '1':
delete() # delete a pw or acces to hidden part
if c == '2':
login() # simple logout system, probably have to change this to something more intermediate
def newdata(): # safes the data in variables and put it in a .txt file
company = input("Enter the companys name: ")
username = input("Enter your username: ")
password = input("Enter your password: ")
print(company + username + password + ", is everything correct?")
a = input("y/n")
if a == "y":
file = open("1.txt", "w")
file.write(
"Company: " + company + "\n" + "Username: " + username + "\n" + "Password: " + password + "\n" + "\n")
file.close()
pwrequest() # return to pwrequest()
if a == "n":
newdata() # return to newdata() if something is incorrect
secretWord = "CompanyUsernamePassword" # define the secret word to finaly acces the hidden part
if company + username + password == secretWord:
secrettest() # go to secrettest() to enter the secret word
def delete(): # just simple code that delete specific content of the pw .txt
name = input("Please enter the Company, Username and password you wanna delete: ")
with open("1.txt", "r") as f:
lines = f.readlines()
with open("1.txt", "w") as f:
for line in lines:
if line.strip("\n") != name:
f.write(line)
def secrettest():
key = Fernet.generate_key()
f = Fernet(key)
truepass = f.encrypt(b"Test1234")
trys = 3
while trys != 0: # checks if you entered the correct pw and if not count 2 times
password = input("Pls enter the password: ")
d = f.decrypt(truepass)
if password == d.decode():
print(truepass)
break
else:
print("Wrong password!")
trys -= 1
if trys == 0:
print("You entered the wrong password to many times!")
if welcome == "1": # should probably try to move that to the top
login()
if welcome == "2": # this too
new_user()
I think I know why the .exe always closes. I executed the .exe in the windows cmd, and got this error "AttributeError: 'Fernet' object has no attribute 'enrcypt'". I'm kinda sure that this is the part that caused the trouble. I'm just wondering why pycharm just ignored this error...
I am a beginner coder here and I am trying to do a simple registration/login system using an external csv file.
my issue--> let's say I have an existing user "john" when my program promts for a name during registration and I enter the letter j or jo or joh
output --> user existed
how can I solve this issue?
import csv
name = input("register your name: ")
name=name.replace(" ", "")
with open("datafile.csv","r") as file:
content=file.read()
loop=True
while loop!=False:
if name in content :
name = input("name taken pls try again: ")
name=name.replace(" ", "")
else:
loop=False
password=input("new password: ")
with open("datafile.csv","a+",newline="") as file:
f=csv.writer(file)
f.writerow([name,password])
def main():
with open("datafile.csv","r") as file:
file_reader = csv.reader(file)
user_find(file_reader)
file.close()
def user_find(file):
user = input("Enter your username: ")
for row in file:
if row[0] == user:
print("username found", user)
user_found = [row[0],row[1]]
pass_check(user_found)
break
else:
print("not found")
def pass_check(user_found):
user = input("enter your password: ")
if user_found[1] == user:
print("password match")
else:
print("password not match")
main()
name in content checks whether name is anywhere in the string content. name may be any string whatsoever, so 'jo' in 'john,his_password' will happily find that 'jo' is indeed a substring of the content and evaluate to True.
You should actually parse the CSV:
existing_names = set() # in case the file is empty
with open("datafile.csv") as file:
existing_names = {
existing_name
for (existing_name, _) in csv.reader(file)
}
while True:
if name in existing_names:
name = input("name taken pls try again: ")
name = name.replace(" ", "")
else:
break
I'm just starting with python and I want to make a simple login system with text files. Everytime I run the code I get this error. It doesn't even make the text file. Before this, I could run my code and it made a file but now it doesn't. I tried just one line of code to open a text file but that doesn't work either.(line of code: f = open("demofile.txt")) I also tried to google it, no solution. I don't know what to do?
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no, please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", 'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
f = open("dataBank.txt", 'w')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", "r")
info = f.read()
info = info.split()
if name in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
i dont know whats your logic but to create a file you need to use a w+
try it by de the code
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no, please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
try:
f = open("dataBank.txt", 'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
except:
return 'Data base donest exists. creating one...'
f = open("dataBank.txt", 'w+')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", "r")
info = f.read()
info = info.split()
if username in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
The error you get in f = open('demofile.txt') is because open takes an additional argument 'mode' whose default value is 'r' for read. If the passed filename does not exist you get the described error.
Use f = open('demofile.txt','w') instead for writing to a file. This creates a new file if the filename does not exist.
I'm aware of the multiple posts and sources regarding how to loop and read from a text file. I'm sorry to be that guy but I'm a recent noob at Python and I'm writing this at 1:00 in the morning.
As the title suggests, how do I loop my login page so that if the user enters details incorrectly then they get another chance to try, until they have entered details correctly. The password/username also needs to be read from an external file.
My code:
print ("\nEnter details to access wallet...\n")
username = 'Janupedia'
password = '12345'
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= £315.37")
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print('\n--------------------------------------------------------\n')
Let's say your text file (credentials.txt) reads:
Janupedia
12345
Maybe something like this will work for you. I've commented the code that I added. You probably want to name the credentials file something else.
print ("\nEnter details to access wallet...\n")
"""
Open File
"""
with open("Credentials.txt", "r") as f:
array = []
for line in f:
array.append(line) #stores username and password
username = array[0]
password = array[1]
login = 0 #initial login status
while login == 0: #as long as login status = 0 loop repeats
userInput = input("Username?")
if username.strip(' \n') == userInput.strip(' \n'):
userInput = input("Password?")
if password.strip(' \n') == userInput.strip(' \n'):
login = 1 #login successful set login status to 1 thus breaking loop
else:
print("Incorrect")
else:
print("Incorrect")
print('\n--------------------------------------------------------\n')
# Login successful loop finished
print("Welcome!")
print('\n--------------------------------------------------------\n')
print ("BTN = 0.10")
print ("= 315.37")
So you want to loop it. Where would a good place for that be? How about when we ask for a question.
Now, look at the condition where we get the right username and password. We don't want to handle it inside the loop. The loop is only there to get the correct username and password.
print("\nEnter details to access wallet...\n")
username = "Janupedia"
password = "12345"
userInput = ""
while userInput != password:
userInput = input("What is your username?\n")
if userInput == username:
userInput = input("Password?\n")
if userInput == password:
break
else:
print("That is the wrong password.")
else:
print("That is the wrong username.")
print("Welcome!")
print("\n--------------------------------------------------------\n")
print("BTN = 0.10")
print("= £315.37")
todo_list = open("Credentials", "a")
todo_list.write("Username = Janupedia + Password = 12345")
todo_list.close()
print("\n--------------------------------------------------------\n")
Now to read your username/password from a file. Let's make it simple. The first line is the username and the second line is the password. There are no other items.
Now create a proper function.
def read_credentials_from_file(filename):
"""Read the file and return (username, password).
File contents are first line username and second line password.
"""
# Using the `with` statement is current best practice.
with open(filepath, "rt") as user:
username = user.readline().strip()
password = user.readline().strip()
return username, password
Now fix your code to use the function.
username, password = read_credentials_from_file(...)
Note in the function we strip line endings. If you are using Python 3.7, use the breakpoint function to step through the code and watch what it is doing.
do something like this:
password = "password"
username = "username"
theirUsername = input("What is your username")
theirPassword = input("What is your password")
while theirUsername != username or theirPassword != password:
print("incorrect")
theirUsername = input("What is your username")
theirPassword = input("What is your password")
print("correct")
You can read from an external file with file = open("externalfile.txt","r") then do text = file.read() and if the file is formatted as
username
password
do text = text.split("\n") and then username = text[0] and password = text[1]
this is what it should look like with an explanation:
file = open("password.txt","r") #this opens the file and saves it to the variable file
text = file.read() #this reads what is in the file and saves it to the variable text
text = text.split("\n") #this makes the text into a list by splitting it at every enter
username = text[0] #this sets the username variable to the first item in the list (the first line in the file). Note that python starts counting at 0
password = text[1] #this sets the password variable to the second item in the list (the second line in the file)
theirUsername = input("What is your username") #gets username input
theirPassword = input("What is your password") #get password input
while theirUsername != username or theirPassword != password: #repeats the code inside while theirUsername is not equeal to username or theirPassword is not equal to password
print("incorrect") #notifies them of being wrong
theirUsername = input("What is your username") #gets new username input
theirPassword = input("What is your password") #gets new password input
print("correct") #tells them they are corrected after the looping is done and the password and username are correct
Here are simple login scripts.
I have little bugs.
In a text file write:
name :test
password :123321
admin :0
I want to do:
if password and username exist then
#do code
else
#do code
import os
import sys
print "Hello to login - login(username,password)"
login = 0
att = 1
while login == 0:
#Check if user login/exist
Log = raw_input("Enter username: ")
if os.path.isfile(Log + ".txt"):
userfile = (Log+".txt")
f = open(userfile,"r")
Pass = raw_input("enter password: ")
Lines = f.readlines()
Password1 = Lines[1].split(":")
Passwordl = Lines[1].strip()
if Passwordl[10:] == Pass:
login = 1
break
elif att == 3:
print "you try to log in more then 3 time, user locked"
break
else:
print "username not exist or pass wrong"
att += 1
if login == 1:
print "Welcome "
You're problem is indenting- you want to indent everything from Log= to be within the while loop
import os
import sys
print "Hello to login - login(username,password)"
login = 0
att = 1
while login == 0:
#Check if user login/exist
Log = raw_input("Enter username: ")
if os.path.isfile(Log + ".txt"):
userfile = (Log+".txt")
f = open(userfile,"r")
Pass = raw_input("enter password: ")
Lines = f.readlines()
Password1 = Lines[1].split(":")
Passwordl = Lines[1].strip()
if Passwordl[10:] == Pass:
login = 1
break
elif att == 3:
print "you try to log in more then 3 time, user locked"
break
else:
print "username not exist or pass wrong"
att += 1