Reputation: 21
I need help with looking for a username in a text file so that the user should enter a username that is not already stored in the file.
The text file looks like this:
aaa12 aaa12
aaa16 aaa16
iii12 iii12
Code:
username=input("Enter a username:")
with open("users.txt") as openfile:
for line in openfile:
for part in line.split():
if username in part:
print("Try again")
I don't think it works. Is there any other solutions I could use?
Upvotes: 0
Views: 74
Reputation: 25895
You're rechecking too many times - you were on the way, but I suggest first collecting, then checking:
users = set()
with open("users.txt") as openfile:
for line in openfile:
users.update(line.split())
#Another way:
#for user in line.split():
#users.add(user)
first = True
while first or (username in users):
if not first: print("Try again, exists!")
username=input("Enter a username:")
first = False
Upvotes: 1
Reputation: 1377
username=input("Enter a username:")
exists = False
with open("users.txt") as openfile:
for line in openfile:
if username in line:
exists = True
if not exists:
print("Try again")
This would handle if you have usernames in multiple lines in the text file. Basically, you don't need all the hoops of splitting in python, which is a beauty really.
Upvotes: 0
Reputation: 42007
You can do the in
(__contains__
) test directly on the string (line
here) itself, no need for split
-ing and making a list:
for line in openfile:
if username in line:
print("Try again")
break
For white separated username (as shown in the example), and each username is a whole match:
for line in openfile:
if username in line.split():
print("Try again")
break
Note that, matching username is never going to be perfect. If simple matching does not work, then probably you should think about picking a suitable container first rather than doing text processing.
Upvotes: 2