Searching for keyword in text file - python

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!

Related

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 to find specific words in a separate text file? (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")

Python password system with lock after certain number of attempts

So I am trying to create a password system in Python, whereby after a certain number of incorrect attempts, the user will be blocked from accessing it for, say, 5 minutes. I am currently unsure how the values of the variables can be kept after rerunning the same file and then used in this manner. Could someone help me with this, as I am currently still new to Python?
Update:
After experimenting for a while with the code Jonas Wolff provided me I finalised my code to the following:
def password():
count = 0
currentTime = float(time.time())
passwordList = ["something", "password", "qwerty", "m42?Cd", "no"]
passwordNum = random.randint(0, 4)
password = passwordList[passwordNum]
with open("password.txt", "r") as file:
check = file.readline()
initialTime = file.readline()
if initialTime=="":
initialTime==0
if int(check)==1 and (currentTime-float(initialTime))<300:
print("You are still locked")
print("Please try again in", int(300-(currentTime-float(initialTime))), "seconds.")
quit()
print("The randomised password is No.", passwordNum+1) #Prints a string to let the user know which password was randomly selected
while count<5:
inp = input("Enter the Password: ")
if inp==password:
print("Access Granted")
print()
f = open("password.txt", "w")
f.write("0\n0")
f.close()
select()
elif (count+1)==5:
print("You have been locked")
print("Please try again in 5 minutes")
f = open("password.txt", "w")
f.write("1\n")
f.write(str(currentTime))
f.close()
quit()
else:
count+=1
print("Incorrect Password")
print("You have", 5-count, "tries left.")
continue
Thanks a lot for the help you have provided and the patience with which you answered my questions.
import YourProgram # this is the program you want to run, if the program runs automaticly when opened then move the import to the part where i wrote YourProgram() and delete the YourPregram() line
import time
pswd = "something"
count = 0
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
numa = file_info.count("1")
count = numa
while True:
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
tima = file.readline()
inp = input("What is the password:")
if inp == pswd:
if tima == "":
tima = "0" # this should solve yoúr problem with float convertion however it doesn't make sence that this step should be needed
if str(file_info[:5]) != "11111" or time.time() > float(tima):
YourProgram() # this is just meant as the thing you want to do when when granted acces i magined you where blocking acces to a program.
f = open("PhysxInit.txt", "w")
f.write("\n")
f.close()
break
else:
count += 1
f = open("PhysxInit.txt", "w")
f.write(("1"*count)+"\n"+str(tima))
if count == 5:
f.write(str(time.time()+60*5))
f.close()
#f = open("PhysxInit.txt", "w")
#f.write("\n")
#f.close()
does this work?
just make sure you have a text file called PhysxInit.txt
after running the program, and having guessed wrong a few times my txt file look like this.
11111
1536328469.9134998
it should look something like mine though the numbers may be diffrent.
To read a specific line as you requested you need to do:
with open("PhysxInit.txt", "r") as f:
for w,i in enumerate(f):
if w == #the number line you want:
# i is now the the line you want, this saves memory space if you open a big file

Looping a Try/Except block until a file can be read

I have a try/except block in a function that asks the user to enter the name of a text file to open. If the file does not exist, I want the program to ask the user for the filename again either until it is located or the user hits ENTER.
Right now the try/except block just runs infinitely.
def getFiles(cryptSelection):
# Function Variable Definitions
inputFile = input("\nEnter the file to " + cryptSelection +\
". Press Enter alone to abort: ")
while True:
if inputFile != '':
try:
fileText = open(inputFile, "r")
fileText.close()
except IOError:
print("Error - that file does not exist. Try again.")
elif inputFile == '':
input("\nRun complete. Press the Enter key to exit.")
else:
print("\nError - Invalid option. Please select again.")
return inputFile
You need to break out of the while loop, this has to be done at 2 places:
After reading the file (when it is a correct file)
After the Enter key is pressed. because we want to end.
Also you need to prompt the question inside the loop so the question is asked again at every iteration and the inputFile value is updated with the latest user input
One last thing, I think your else clause can be removed as it is never accessed, the if and elif catch all the possibilities (ie, inputFile has a value or not).
def getFiles(cryptSelection):
while True:
inputFile = input("\nEnter the file to %s. Press Enter alone to abort:" % cryptSelection)
if inputFile != '':
try:
fileText = open(inputFile, "r")
fileText.close()
# break out of the loop as we have a correct file
break
except IOError:
print("Error - that file does not exist. Try again.")
else: # This is the Enter key pressed event
break
return inputFile
you have a while True but no break in your code you probably want to break after the fileText.close() like this:
try:
fileText = open(inputFile, "r")
fileText.close()
break
except IOError:
print("Error - that file does not exist. Try again.")
but really you should change this check to use os.path.isfile like this:
import os
def getFiles(cryptSelection):
inputFile = input("\nEnter the file to " + cryptSelection +\
". Press Enter alone to abort: ")
while True:
if inputFile != '':
if os.path.isfile(inputFile):
return inputFile
else:
print("Error - that file does not exist. Try again.")
elif inputFile == '':
input("\nRun complete. Press the Enter key to exit.")
else:
print("\nError - Invalid option. Please select again.")
That is because you don't assign a new value to inputFile within the while loop.
It will hold the same value forever...
EDIT
Once you will assign a new value to inputFile within the loop - make sure to break out when the exit condition is met ("user hits Enter")

checking if word exists in a text file python

I'm working with Python, and I'm trying to find out if a word is in a text file. i am using this code but it always print the "word not found", i think there is some logical error in the condition, anyone please if you can correct this code:
file = open("search.txt")
print(file.read())
search_word = input("enter a word you want to search in file: ")
if(search_word == file):
print("word found")
else:
print("word not found")
Better you should become accustomed to using with when you open a file, so that it's automatically close when you've done with it. But the main thing is to use in to search for a string within another string.
with open('search.txt') as file:
contents = file.read()
search_word = input("enter a word you want to search in file: ")
if search_word in contents:
print ('word found')
else:
print ('word not found')
Other alternative, you can search while reading a file itself:
search_word = input("enter a word you want to search in file: ")
if search_word in open('search.txt').read():
print("word found")
else:
print("word not found")
To alleviate the possible memory problems, use mmap.mmap() as answered here related question
Previously, you were searching in the file variable, which was 'open("search.txt")' and since that wasn't in your file, you were getting word not found.
You were also asking if the search word exactly matched 'open("search.txt")' because of the ==. Don't use ==, use "in" instead. Try:
file = open("search.txt")
strings = file.read()
print(strings)
search_word = input("enter a word you want to search in file: ")
if(search_word in strings):
print("word found")
else:
print("word not found")

Categories

Resources