简体   繁体   中英

How to find specific words in a separate text file? (PYTHON)

Im doing a homework assignment and will need to locate a specific word in python. Any help would be much appreciated. I am quite new to coding. I would like help on how to answer this question.

I have seen multiple tutorial's but none have helped me so far.

y=()
answer=str(input("Do you want to create an account, y or n?"))
if answer=="y":
  file = open("database.txt", "r")
  username = input("Enter a username :")
  password = input("Now enter a password :")
  file = open("database.txt","a")
  file.write (username)
  file.write (",")
  file.write (password)
  file.write("\n")
  file.close()

else:
  username1=input("Enter your username:") 
  password1=input("Now enter your password:") 
  for line in open("database.txt","r").readlines():
    login_info = line.split()
  if username1 == login_info and password1 == login_info:
    print("Incorrect")
  else:
    print("Correct")

I expected the output to say correct when all the criteria is met but instead it outputs correct when i enter anything.

The indentation in the second part of your code is messed up, because the if- and else-statement should be inside of the for loop. Also you split the loaded lines into a list ( login_info ) but incorrectly check that against the username and password variables. And you use the default split() function which uses a whitespace as a separator, but you use a comma. I also put the else statement out of the for loop, because otherwise it will print every time the line is not the one where the user is stored. Try this for the second part:

else:
  username1=input("Enter your username:") 
  password1=input("Now enter your password:") 
  for line in open("database.txt","r").readlines():
    login_info = line.split(",")
    if username1 == login_info[0] and password1 == login_info[1].replace("\n", ""):
       print("Correct")
       break #Exit the for loop if the user is found
  else: #Only executed when break is not called
    print("incorrect")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM