0

I am programming a dice game that only allows authenticated users to play, I have a method of appending and creating a password to a file. But I cannot search for a specific password that the user enters. My main goal for the section of the program is to create an 'if' statement that checks if the computer has found the specific password or not.

I am new to using the find statement, I have looked through many questions and examples over the past few days to no avail - I cannot get my head around how it would work with my code.

def Lock_Screen():
    print("Welcome")

    print("Log in(1) or Sign up(2)") 
    User_Choice = input("")

    if User_Choice == "1":
        print("Input your three-digit code:")
        UserInput = input(str(""))
        x = open("PasswordList.txt" , "r")
        x.find(Userinput)
        if x.find(UserInput):
            Start_Screen()



    elif User_Choice == "2":        
        Password = random.randint(100,999)
        f = open("PasswordList.txt" , "a+")
        x = open("PasswordList.txt" , "r")
        PasswordList = x.read()
        while Password == PasswordList:                 
            Password = random.randint(100,999)  



        print("This is your password:    " , Password)
        f = open("PasswordList.txt" , "a+")                      
        f.write(str(Password))            
        f.close()
        Lock_Screen()


    else:                                    
        print("That was not a valid answer") 
        Lock_Screen()       

Lock_Screen()

The .find statement is suppose to find the variable but it just returns with an error message.

Kian L
  • 73
  • 8
  • Possible duplicate of [Search File And Find Exact Match And Print Line?](https://stackoverflow.com/questions/15718068/search-file-and-find-exact-match-and-print-line) – tripleee Jan 16 '19 at 08:19
  • From help(open): Open a file using the file() type, returns a file object. open() returns the file object. You need to read the contents of the file using this file object and search the contents in the data that's read. So, first do a x.read() (or x.readlines()), store the output in a variable (say data) and then do a data.find(). Note, it may not yield the accurate result as find() returns the lowest index in S where substring sub is found. So, you may want to do an exact comparison - say read line by line and match each line against the expected password. – Sharad Jan 16 '19 at 08:20

1 Answers1

1

Open files do not have a method named find. You seem to be looking for

Userinput = input("Input your three-digit code: ")

with open(filename) as x:
    for line in x:
        if line.rstrip('\n') == Userinput:
            print("password correct")
            break
    else:
        print("password not found")

The with context manager takes care of closing the open file handle when you are done.

tripleee
  • 175,061
  • 34
  • 275
  • 318