The function f3.read()
is reading the entire file at once, and moving the file pointer to the end. Any subsequent file read without closing and reopening the file is going to return None
.
You need to actually parse the file into a data structure that allows you to search for containment, instead of checking to see if the name or password exists in the entire file. What happens if two users have the same password? If you're just searching for a single string through the whole file, you're not ensuring that a password is correct for the given username.
For example, assume your file looks something like this:
username1,password1
username2,password2
username3,password3
Your parsing code should open and read the file, and check for containment without searching the whole file every time:
users = {}
with open("helloworld.txt") as f3:
for line in f3:
name, password = line.split(",")
users[name] = password.strip()
user = input("Enter login name: ")
if user in users:
passw = input("Enter password: ")
print()
if passw == users[user]:
print("Login successful!")
else:
print("Bad password")
else:
print("Bad username")
Note that I changed your file open to use a context manager (the keyword with
). You should do this for more reliable resource management. You could also make further improvements by make the dictionary generation a dictionary comprehension, and possibly by using exceptions to handle the dictionary checking instead of if X in Y
:
with open("helloworld.txt") as f3:
pairs = (line.split(",") for line in f3)
users = {name:password.strip() for name, password in pairs}
user = input("Enter login name: ")
passw = input("Enter password: ")
try:
if passw == users[user]:
print("Login successful!")
else:
print("Bad password")
except KeyError:
print("Bad username")
You could even condense the user/password dictionary creation into a single comprehension, but I think that hampers readability significantly without any benefit.