How to find specific words in a separate text file? (PYTHON) - python

Im doing a homework assignment and will need to locate a specific word in python. Any help would be much appreciated. I am quite new to coding. I would like help on how to answer this question.
I have seen multiple tutorial's but none have helped me so far.
y=()
answer=str(input("Do you want to create an account, y or n?"))
if answer=="y":
file = open("database.txt", "r")
username = input("Enter a username :")
password = input("Now enter a password :")
file = open("database.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
else:
username1=input("Enter your username:")
password1=input("Now enter your password:")
for line in open("database.txt","r").readlines():
login_info = line.split()
if username1 == login_info and password1 == login_info:
print("Incorrect")
else:
print("Correct")
I expected the output to say correct when all the criteria is met but instead it outputs correct when i enter anything.

The indentation in the second part of your code is messed up, because the if- and else-statement should be inside of the for loop. Also you split the loaded lines into a list (login_info) but incorrectly check that against the username and password variables. And you use the default split() function which uses a whitespace as a separator, but you use a comma. I also put the else statement out of the for loop, because otherwise it will print every time the line is not the one where the user is stored. Try this for the second part:
else:
username1=input("Enter your username:")
password1=input("Now enter your password:")
for line in open("database.txt","r").readlines():
login_info = line.split(",")
if username1 == login_info[0] and password1 == login_info[1].replace("\n", ""):
print("Correct")
break #Exit the for loop if the user is found
else: #Only executed when break is not called
print("incorrect")

Related

How to check if only a part of a variable is next to a string in Python?

I'm trying to get my code to check if a word is already in the document. However when choosing a variable (username) that happens to share the same letters going to the right as the preexisting one in the file, it thinks that the name is taken. For example, if abcdefg was in the file, if I was to right defg or fg or g, it would think the username was taken.
def register():
print("━━━━ACCOUNT CREATION━━━━")
username = input("Create Username: ")
with open("Login.txt", "r") as loginfile:
if (username+",") in loginfile.read():
print("Sorry, but that username is taken.")
choice = input("Try again with a new name? (Y/N)")
choice = choice.upper()
My case:
Say I had the name, Joe which is already in the file. If I tried to make a username that is just e, then it would think it is Joe, as it is looking for the e, next to a comma.
Anyway to fix this? Thanks!
This should work
with open('login.txt', 'r') as LoginFile:
# the split function splits a string to a list on mark
Data = LoginFile.read().split(" ,")
if username in Data:
# .....
if this isn't what you want try this built-in module :
https://docs.python.org/3/library/re.html
def register():
print("━━━━ACCOUNT CREATION━━━━")
# read the names from the file
with open('Login.txt', 'r') as f:
names = f.read().split(',')
username = input("Create Username: ")
for name in names:
# check if any names end with this name have been created
if name.endswith(username):
# found
print("Sorry, but that username is taken.")
# we want to keep ask the user to select if
# they enter something other than Y/N
while True:
# ask for the option
option = input("Try again with a new name? (Y/N) ")
# try again, we just rerun this function
if option == 'Y':
register()
# don't ask any more
break
elif option == 'N':
# exit if user chooses N
break
# if the user chooses something else, continue
# the loop and keep asking
# if no names end with username, goto else
break
else:
# name available, save it to the file
print("Name created successfully:", username)
new_names = names + [username]
with open('Login.txt', 'w') as f:
f.write(','.join(new_names))
I have tested it, please try and see if it works for you.

Is there any easy way to check for duplicates in a text file in Python?

There's one last feature I want for my bank account system.
I want it to check if a username has already been saved to the text file database. If the username already exists, then it should tell the user that they can't have that name option. If not, then they would be able to use it.
The rest of my code works as it should, it's just the fcat that I can't append/update my text file properly and see if usernames already exist in the text file database.
import sys
users = {}
status = ""
# Functions ---------------------------------------------------------------------------------------------------------
# Select either account creation or login
def displayMenu():
global status
status = input("Are you a registered user? \n1 - Yes \n2 - No \nQ - Quit \n")
if status == '1':
oldUser()
elif status == '2':
newUser()
else:
print("Unknown input error, exiting . . . .")
sys.exit(0)
return status
# Account creation
def newUser():
global createLogin
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print ("\nLogin name already exists!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nAccount created!\n")
#---- Storing the username in a txt file
file = open("accountfile.txt", "a")
file.write(createLogin)
file.write("\n")
file.close()
oldUser()
# Account login
def oldUser():
global login
login = input("Enter login name: ")
passw = input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
file = open("accountfile.txt", "r")
for text in file: ######## This is where I'm trying to compare username duplicates
if text in file == createLogin:
print("Username already exists!")
print("\nLogin successful!\n")
Bank_Account()
else:
print("\nUser doesn't exist or wrong password!\n")
print("Restarting. Please enter details correctly . . . . .")
sys.exit(0)
class Bank_Account:
def __init__(self):
self.balance=0
response = ''
def deposit(self):
try:
amount=float(input("Enter amount to be Deposited: "))
except ValueError:
print("Enter digits only")
else:
self.balance += amount
print("\n Amount Deposited:",amount)
def withdraw(self):
try:
amount = float(input("Enter amount to be Withdrawn: "))
if self.balance>=amount:
self.balance-=amount
print("\n You Withdrew:", amount)
except ValueError:
print("Enter digits only")
s.withdraw()
else:
print("\n ")
def display(self):
print("\n Remaining Balance=",self.balance)
displayMenu()
s = Bank_Account()
# Calling functions with that class object
s.deposit()
s.withdraw()
s.display()
So it looks you are are writing the user input in the file accountfile.txt. So after a few users log in it might look something like:
$ cat accountfile.txt
mike
sarah
morgan
lee
The section of your code in question is here:
file = open("accountfile.txt", "r")
for text in file:
if text in file == createLogin:
print("Username already exists!")
This particular part is probably not doing what you think it's doing:
if text in file == createLogin
...
if text in file is returning either True or False.
...
So the line above is essentially saying
if False == createLogin
or
if True == createLogin
I believe what you want to do is check if a name is in accountfile.txt. The smallest change you could make to your code in order to achieve that would be
file = open("accountfile.txt", "r")
for text in file:
if text.strip() == createLogin: # .strip() will clean up the \n
print("Username already exists!")
This line:
if text in file == createLogin: is where you are making a mistake. The line is essentially saying:
"(if the text is in the file) compare the result of that check with the string createLogin".
i.e. if (True/False) == createLogin, which is always false because the True/False boolean primitives are never equal to any string (if it actually runs, i have not tested to see if an exception will be thrown).
what you should do is this
for text in file: # get one line of text
if createLogin == text.strip(): # compare the line with the user input string
print("Username already exists!")
break
.strip() removes any leading or trailing spaces in the database stored name (in this case the line break character \n used to denote the end of a line in the file. break ends the loop prematurely cos your lookup is complete since you found what you were looking for, and it would be an unnecessary to continue comparing the user input with other strings, imagine the txt had 1000 names and the 1st name was a match, the user would see the error printed but the program would continue running for the rest of the 999 tries, making it seem sluggish and waste unnecessary CPU cycles.
The database is still case sensitive however which may or may not be desired depending on your requirements. For case insensitivity you could do the following:
for text in file: # get one line of text
if createLogin.lower() == text.strip().lower(): # compare the line with the user input string
print("Username already exists!")
break
.lower() makes both strings into lower case strings and then checks if they are the same, eliminating the case sensitivity.
Instead of writing to the text file, try pickling the database.
This will save a representation of the object that you can easily load back into your program.
import pickle
users = {}
users["Ash"] = "password"
pickle.dump(users, open("users.p", "wb"))
loaded_users = pickle.load(open("users.p", "rb"))
print(loaded_users)
A more advanced solution may also be to check out a relational database, such as [sqlite3][1]

How do I loop my password/username login page and read the password/username from an external file?

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

How can I see if my password variable is within a line so that my code can proceed?

I am creating a password re-setter for school, and i want to check that if the password is within the first line of the text file, then it can say "Okay, choose a new password")
Newpass=""
Network=""
setpass=""
Newpass=""
password=""
def newpass():
Network=open("Userandpass.txt")
lines=Network.readlines()
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password in line:
newpass=input("Okay, choose a new password ")
Network.close()
Network=open("Userandpass.txt","a")
if len(newpass)>= 8 and newpass[0].isalnum()==True and newpass[0].isupper()==True:
print('password change successful')
Network.write("New Password : " + newpass )
Network.close()
break
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
Network=open("Userandpass.txt","w")
Network.write(input("What is your Username")+",")
Network.write(input("Password:")+ ",")
question=input("Do you want to change your password?")
if question=="yes":
Network.close()
newpass()
else:
Network.close()
print("Okay thank you.")
Please help! I have been looking all over here and i can't find a solution
You can try by two things :
lines=Network.read() # change here
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password == lines.split(",")[1]: # change here also
Explanation :
The problem with readlines is o/p as list where read return as string which is better one to use here .
The second thing it returns as a single string ie, combined form of name and password just with ,. So if you split it you will get an list of separated values. Then you can take only password from it and check with input.
In your code you are just checking the input element is just present in that whole string, not checking whether it is same password or not
You said you needed this for school, so i assume it's somewhat urgent:
All the changes i did are minor and i commented what i did and why.
# no need to intialize these variables
#Newpass=""
#Network=""
#setpass=""
#Newpass=""
#password=""
def newpass():
# the with open() construct takes care of closing the file for you and gives you a nice handle for working with the file object.
with open("Userandpass.txt") as Network:
# this reads all filecontents into a list and while doing so strips away any kind of whitespace.
username,current_password=[x.strip() for x in Network.readlines()]
for i in range (3):
password=input("just to confirm it is you, re-enter your old password: ")
if password == current_password:
# communicate the requirements instead of letting potential users run into errors
newpass=input("Okay, choose a new password (must be 8 chars or more, alphanumeric and have it's first letter capitalized.) ")
if len(newpass)>= 8 and newpass.isalnum() and newpass[0].isupper():
with open("Userandpass.txt","a") as Network:
print('password change successful')
Network.write("New Password : " + newpass )
return
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
with open("Userandpass.txt","w") as pwfile:
# separate by newline instead of punctuation => personal preference
pwfile.write(input("What is your Username? ")+"\n")
pwfile.write(input("Password: ")+ "\n")
question=input("Do you want to change your password? (yes/no): ")
if question[0].lower() == 'y':
newpass()
else:
print("Okay thank you.")
# properly terminate
exit(0)
You are missing an 's' in the line
if password in line**s**:
maybe the problem comes from there.

Searching for keyword in text file

I have a list of passwords in a text file called "SortedUniqueMasterList.txt". I'm writing a program that takes user input and checks to see if the inputted password is in the list.
Here is my code:
Passwords = []
with open("SortedUniqueMasterList.txt", "r", encoding = "latin-1") as infile:
print("File opened.")
for line in infile:
Passwords.append(line)
print("Lines loaded.")
while True:
InputPassword = input("Enter a password.")
print("Searching for password.")
if InputPassword in Passwords:
print("Found")
else:
print("Not found.")
However, every password that I enter returns "Not found.", even ones that I know for sure are in the list.
Where am I going wrong?
After reading lines in your file, each entry in your Passwords list will contain a "new line" character, '\n', that you will want to strip off before checking for a match, str.strip() should allow keywords to be found like this:
for line in infile:
Passwords.append(line.strip())
Something closer to this runs - when you read a file, you can read each line in as an array element. try this let mme know how it goes
with open("SortedUniqueMasterList.txt", "r") as infile:
print("File opened.")
Passwords = infile.readlines()
print("Lines loaded.")
while True:
InputPassword = input("Enter a password.")
InputPassword = str(InputPassword)
print("Searching for password.")
if InputPassword in Passwords:
print("Found")
else:
print("Not found.")
The issue is that you cannot look for a substring in a python list. You must loop through the list checking if the substring is found in any of the elements, then determine if it was found or not.
Passwords = []
with open("SortedUniqueMasterList.txt", "r", encoding = "latin-1") as infile:
print("File opened.")
for line in infile:
Passwords.append(line)
print("Lines loaded.")
while True:
InputPassword = input("Enter a password.")
print("Searching for password.")
found = False
for i in Passwords:
if InputPassword in i:
found = True
break
if found:
print("Found.")
else:
print("Not found.")
I think this is a problem I've had, maybe it is, maybe it isn't. The problem is called a trailing newline. Basically, when you press enter on a text document, it'll enter a special character which indicates it's a new line. To get rid of this problem, import the module linecache. Then, instead of having to open the file and close it, you do linecahce.getline(file, line).strip().
Hope this helps!

Categories

Resources