I want to use recursion and binary search to search a text file for a username and password. Each account (username and password) are saved on one line, with a space separating the two.
This is what I currently have (does work), just want to use more techniques:
def validation(username1, password1):
file = open("Accounts.txt", "r")
for line in file:
line = line.split("\n")
line = line[0].split(" ")
if username1 == line[0] and password1 == line[1]:
main_menu() #main_menu() will allow the user to enter the game
else:
valid = Label(root, text="Account not found try again or sign up")
valid.place(x=215, y=130)
login() #will recall the login window and ask them to renter details
file.close()
I have the following code which I want to use:
def validation(username1, password1):
file = open("Accounts.txt", "r")
userame1 and passwrod1 are the details that the user have entered. I now want to check that an account has already been created using binary search and recursion.
Amy ideas on how to do this? I'm still learning how to code.
The simplest way would be to read all lines and sort them, so that binary search can be applied.
def validation(username1, password1):
file = open("Accounts.txt", "r")
lines = [i.strip().split() for i in file.readlines()]
# lines is a list of [username, password] sublists
lines.sort()
if binary_search(lines, [username1, password1]):
login()
else:
print(“User Not Found”)
you can try to see if a specific word is in the text file:
def validation(username1, password1):
file = open("Accounts.txt", "r")
content = file.read()
if str(username1) and str(password1) in content:
return True
else:
return False
And then call main_menu() or login() depending of the result of validation()
Related
Programme that checks if password is in file. File is from a different programme that generates a password. The problem is that I want to check if the exact password is in the file not parts of the password. Passwords are each on newlines.
For example, when password = 'CrGQlkGiYJ95' : If user enters 'CrGQ' or 'J95' or 'k' : the output is true. I want it to output True for only the exact password.
I tried '==' instead of 'in' but it outputs False even if password is in file. I also tried .readline() and .readlines() instead of .read(). But both output false for any input.
FILENAME = 'passwords.txt'
password = input('Enter your own password: ').replace(' ', '')
def check():
with open(FILENAME, 'r') as myfile:
content = myfile.read()
return password in content
ans = check()
if ans:
print(f'Password is recorded - {ans}')
else:
print(f'Password is not recorded - {ans}')
One option assuming you have one password per line:
def check():
with open(FILENAME, 'r') as myfile:
return any(password == x.strip() for x in myfile.readlines())
Using a generator enables to stop immediately if there is a match.
If you need to repeat this often, the best would be to build a set of the passwords:
with open(FILENAME, 'r') as myfile:
passwords = set(map(str.strip, myfile.readlines()))
# then every time you need to check
password in passwords
So basically I am making a program that writes the .txt file and changes the names in form by last to first like Woods, Tiger and turn them into usernames in this form twoods. They have to be formatted all in lower case and I think I messed up my code somewhere. Thanks!
The code I tried, below:
def main():
user_input = input("Please enter the file name: ")
user_file = open(user_input, 'r')
line = user_file.readlines()
line.split()
while line != '':
line = user_file.readline()
print(line.split()[-1][0][0:6]+line.split()[0][0:6]).lower() , end = '')
user_file.close()
if __name__ == "__main__":
main()
try this:
line = "Tiger Woods"
(fname, lname) = line.split(" ")
print(f'{fname[0:1]}{lname}'.lower())
There appear to be a couple of little issues preventing this from working / things that can be improved,
You are trying to split a list which is not possible. This is a string operation.
You are manually closing the file, this is not ideal
The program will not run as you are not using __name__ == "__main__"
Amended code,
def main():
user_input = input("Please enter the file name: ")
with open(user_input, 'r') as file_handler:
for line in file_handler:
print((line.split()[-1][0][0:6] + line.split()[0][0:6]).lower(), end='')
if __name__ == "__main__":
main()
If i understand your problem correctly, you want to read Surname,Name from a file line by line and turn them into nsurname formatted usernames.
For that, we can open and read the file to get user informations and split them line by line and strip the \n at the end.
After that, we can loop the lines that we read and create the usernames with given format and append them to an array of usernames.
Code:
# Get filename to read.
user_input = input("Please enter the file name: ")
# Open the given file and readlines.
# Split to lines and strip the \n at the end.
user_names = []
with open(user_input,'r') as user_file:
user_names = user_file.readlines()
user_names = [line.rstrip() for line in user_names]
print("User names from file: " + str(user_names))
# Loop the user informations that we read and split from file.
# Create formatted usernames and append to usernames list.
usernames = []
for line in user_names:
info = line.split(',')
username = (info[1][0:1] + info[0]).lower()
usernames.append(username)
print("Usernames after formatted: " + str(usernames))
Input File(test.txt):
Woods,Tiger
World,Hello
Output:
Please enter the file name: test.txt
User names from file: ['Woods,Tiger', 'World,Hello']
Usernames after formatted: ['twoods', 'hworld']
I have a file which contains my passwords like this:
Service: x
Username: y
Password: z
I want to write a method which deletes one of these password sections. The idea is, that I can search for a service and the section it gets deleted. So far the code works (I can tell because if you insert print(section) where I wrote delete section it works just fine), I just don't know how to delete something from the file.
fileee = '/home/manos/Documents/python_testing/resources_py/pw.txt'
def delete_password():
file = open(fileee).read().splitlines()
search = input("\nEnter Service you want to delete: ")
if search == "":
print("\nSearch can't be blank!")
delete_password()
elif search == "cancel":
startup()
else:
pass
found = False
for index, line in enumerate(file):
if 'Service: ' in line and search in line:
password_section = file[index-1:index+3]
# delete password_section
found = True
if not found:
print("\nPassword for " + search + " was not found.")
delete_password()
Deleting a line from the file is the same as re-writing the file minus that matching line.
#read entire file
with open("myfile.txt", "r") as f:
lines = f.readlines()
#delete 21st line
del lines[20]
#write back the file without the line you want to remove
with open("myfile.txt", "w") as f:
f.writelines(lines)
I have recently asked a question and received an answer that I must 'pickle' my code. As a beginner, I have no idea how to do that.
This was my code:
users = []
users.append([username, password])
usersFile = open("users.txt","w+")
for users in users:
usersFile.write("%s" % users)
usersFile.close()
def loginFunction():
userEntry = ""
foundName = 0
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
lines = usersFile.readlines()
for i, user in enumerate(users):
if userEntry == users[index][0]:
foundName = 1
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == users[index][1]:
print "Username and passwords are correct"
break
else:
print "incorrect"
userEntry = ""
if foundName == 0:
print "Username not recognised"
userEntry = ""
My problem was that I was never receiving an "Enter your password" despite knowing that the username I was entering was in fact in the text file in that list. I kept getting "Username not found back" even though I knew it was there. There was mention of not having referred back to lines but again, not sure how I would go about doing that. If someone could help me out by changing up my code and explaining that would be fantastic. I have been referred to documents trying to explain it and have done by own research on the topic but none of it makes sense to me. A written example in this context would help me out a lot.
So, if I understood correctly by looking at the other two questions (1 and 2) you made related to this, your problem has two parts:
One is generating a file with a list of user/passwords and the second is using that file to do a "login" system.
The problem with writing to files is that you can regard a file as just text... It doesn't really retain the concept of a Python list so you need to figure out a way to convert your fancy users list of lists to text and then back to a list of lists so you can actually use it.
There are many pre-made serializing formats. Here are a few: JSON, CSV, YAML, or the one another user recommended in another question, Pickle
Since in another post you mentioned that you're using this for learning purposes, let's try to keep it as simple as possible ok?
Let's split your exercise in two python files: One to just generate the passwords file and the other that tries to read and verify the username/password that the user entered.
Script 1: Generate the password file.
So... You have a list of username/password pairs, and you have to transform that to text so you can store it in a file. Let's just go through each entry in the list and write it to a file. How about using a bit of inspiration from Linux and use the semicolon character (;) to mark the separation between username and password on each line of the file? Like this:
sample_users = [
["user1", "password1"],
["user2", "password2"],
["user3", "password3"]
]
users_file = open("./users.txt", "w")
for sample_user in sample_users:
username = sample_user[0]
password = sample_user[1]
users_file.write(username + ';' + password + '\n')
users_file.close()
Put that in a .py file and run it. It should generate a file called users.txt right on the same directory where the script is located. I suggest you take a look to the file (any text editor will do). You'll see it looks like this:
user1;password1
user2;password2
user3;password3
By the way, it's a much better practice taking advantage of the "autoclosing" features provided by Python's context managers. You could write that script as:
with open("./users.txt", "w") as users_file:
for sample_user in sample_users:
username = sample_user[0]
password = sample_user[1]
users_file.write(username + ';' + password + '\n')
See? No call to .close() needed. If something happens while running the code, you will be assured that your file is closed after leaving the with block (when the interpreter reaches the end of the with block, a call to the File's special function __exit__ will be automatically run, and the file will be closed)
Script 2: Use the passwords file
Ok... So we have a file with username;password\n on each line. Let's use it.
For this part, you're gonna need to understand what the split (to separate username and password using the semicolon) and rstrip (to remove the newline symbol \n at the end) methods of the str objects do.
We're gonna need to "rebuild" two variables (username and password) from a line of text that has the shape username;password\n. Then see if the username is found in the file, and if so, prompt the user for the password (and verify it's correct):
def loginFunction():
userEntry = ""
foundName = False
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
for line in usersFile:
print("This is the line I read:%s", line,)
# Read line by line instead of loading the whole file into memory
# In this case, it won't matter, but it's a good practice to avoid
# running out of memory if you have reaaaally large files
line_without_newline = line.rstrip('\n') # Remove ending \n
user_record = line_without_newline.split(';') # Separate into username and password (make the line a list again)
userName = user_record[0]
password = user_record[1]
# Might as well do userName, password = line_without_newline.split(';')
if userName == userEntry:
foundName = True
print("User found. Verifying password.")
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == password:
print "Username and passwords are correct"
break
else:
print "incorrect"
userEntry = ""
if not foundName:
print("Username not recognised")
userEntry = ""
if __name__ == "__main__":
loginFunction()
I believe this should do what you want? Put a comment in the answer if you have other questions.
And have fun coding!
PS: So... How about pickle?
Pickle is a module that serializes Python objects into files in a "safer" and more automated way. If you wanted to use it, here's how (one way, at least):
Generating the passwords file:
import pickle
sample_users = [
["user1", "password1"],
["user2", "password2"],
["user3", "password3"]
]
with open('./users.txt', 'w') as f:
pickler = pickle.Pickler(f)
for sample_user in sample_users:
pickler.dump(sample_user)
As before, at this point I would recommend you take a look to how the file users.txt looks like with a regular text editor. You'll see it's pretty different to the file before (the one with the username and password separated by semi colons). It's something like this:
(lp0
S'user1'
p1
aS'password1'
p2
a.(lp3
S'user2'
p4
aS'password2'
p5
a.(lp6
S'user3'
p7
aS'password3'
p8
a.%
Use the file:
import pickle
def loginFunction():
userEntry = ""
while userEntry == "":
userEntry = raw_input("Enter your username: ")
usersFile = open("users.txt", "r")
unpickler = pickle.Unpickler(usersFile)
while True:
try:
user_record = unpickler.load()
userName = user_record[0]
password = user_record[1]
if userName == userEntry:
print("User found. Verifying password.")
passwordEntry = raw_input("Enter your password: ")
if passwordEntry == password:
print "Username and passwords are correct"
else:
print "incorrect"
userEntry = ""
# Watch out for the indentation here!!
break # Break anyway if the username has been found
except EOFError:
# Oh oh... the call to `unpickler.load` broke
# because we reached the end of the file and
# there's nothing else to load...
print("Username not recognised")
userEntry = ""
break
if __name__ == "__main__":
loginFunction()
If you realize, when you do user_record = unpickler.load(), you already get a 2 items Python list in the user_record variable. There's no need for you to transform from text onto list: the unpickler has already done that for you. This is possible thanks to of all that "extra" information that was stored by picker.dump into the file, which allows the unpickler to "know" that the object that needs to be returned is a list.
This is the way you create a login system with pickle however i don't recommend this as there is lot of security issue.I would prefer connecting python to SQL server and storing password in the database.
import pickle
def register(username,password):
user_details = dict()
with open("users.txt",'rb') as f:
user_details = pickle.load(f)
if username in user_details:
print "User already exsits"
else:
user_details[username] = password
print "User added successfully"
with open("users.txt",'wb+') as f:
pickle.dump(user_details,f)
def login(username,password):
user_details = dict()
with open("users.txt",'rb') as f:
user_details = pickle.load(f)
if username in user_details:
if user_details[username] == password:
print "Correct Login successful"
else:
print "Incorrect Details"
def init():
user_details = dict()
with open("users.txt",'wb+') as f:
pickle.dump(user_details,f)
init()
register("s","s")
login("s","s")
To initialise call the init() function.
so im writing a login system with python and i would like to know if i can search a text document for the username you put in then have it output the line it was found on and search a password document. if it matches the password that you put in with the string on that line then it prints that you logged in. any and all help is appreciated.in my previous code i have it search line one and if it doesnt find the string it adds one to line then repeats till it finds it. then it checks the password file at the same line
def checkuser(user,line): # scan the username file for the username
ulines = u.readlines(line)
if user != ulines:
line = line + 1
checkuser(user)
elif ulines == user:
password(user)
Pythonic way for your answer
f = open(filename)
line_no = [num for num,line in enumerate(f) if 'searchstring' in line][0]
print line_no+1
fucntion to get the line number. You can use this how you want
def getLineNumber(fileName, searchString):
with open(fileName) as f:
for i,line in enumerate(f, start=1):
if searchString in line:
return i
raise Exception('string not found')