CodeManYote
CodeManYote

Reputation: 9

Searching through text files using loops

I am trying to create a very simple piece of code which will search through a text file to see if a username has been registered or not. However I am unsure how to search through the text file to find a match for the username.

Here is my code so far:

NotLoggedIn = False
while NotLoggedIn == False:
    username = input("\nplease enter a username or to sign in type '!'")
    for next in records:
        if username == records:
            print("hi")
            NotLoggedIn = True

Thanks in advance.

Upvotes: 0

Views: 183

Answers (2)

amirhosein majidi
amirhosein majidi

Reputation: 149

It depends on how you wrote your text file. if that text file is like this : username1\nusername2\n ... Then we can code like this :

f = open("records.txt","r")
m = f.readlines()
f.close()
NotLoggedIn = False
while NotLoggedIn == False:
    username = input("\nplease enter a username or to sign in type '!'") 
    for line in m :
        if line.replace("\n","") == username :   # removing "\n" from the line 
            print("hi")
            NotLoggedIn = True  
            break       # No need to check others 

It is important to be specific. You shouldn't use "in" to find a username inside of a string, because if you have a username called string then if someone types str , it will be like this :

if "str" in "string" 

Witch will be true But it doesn't exist in your text file. So try using "==" operator.

Upvotes: 0

Sheldore
Sheldore

Reputation: 39042

Here is what you can try provided you have a textfile named records.txt since as per your question you need to search through a text file.

f = open("records.txt", 'r') 

NotLoggedIn = False
while NotLoggedIn == False:
    username = input("\nplease enter a username or to sign in type '!'")
    for line in f.readlines():
        if username in line:
            print("hi, username exists in the file")
            NotLoggedIn = True
            break

if not NotLoggedIn:
    print ("User does not exist in the file")

f.close()            

Upvotes: 1

Related Questions