如何在单独的文本文件中找到特定的单词? (蟒蛇)

时间:2019-06-02 10:05:06

标签: python

我正在做作业,需要在python中找到一个特定的单词。任何帮助将非常感激。我是编码新手。我希望如何回答这个问题有帮助。

我看过多个教程,但到目前为止都没有帮助。

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")

我希望输出在满足所有条件时都说正确,但是当我输入任何内容时输出就正确。

1 个答案:

答案 0 :(得分:2)

代码第二部分的缩进被弄乱了,因为if-和else-语句应该位于for循环的内部。另外,您将加载的行拆分为一个列表(login_info),但根据用户名和密码变量错误地进行了检查。并且您使用默认的split()函数,该函数使用空格作为分隔符,但使用逗号。我还将else语句放在for循环之外,因为否则它将在每行不是存储用户的行时打印。尝试第二部分:

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")