Python没有查找文件中的字符串?

时间:2017-10-19 19:29:44

标签: python python-3.x io

我正在尝试让Python 3.5在文件中查找变量。我试图将username转换为str(username),但无济于事。这是令人讨厌的代码:

if str(username) in fi.read():
         hasAccount = True
         print("found username")
      else:
         hasAccount = False
         print("notfound")

有什么想法吗?这个让我非常困惑。 感谢

P.S。我之前已在代码中使用过with open("usernames.txt", "a+")as fi:

P.P.P.S。人们要求MCVE,所以我希望这很重要:

with open("usernames.txt", "a+")as fi:#opens usernames file as "fi" and closes once finished
with open("userinfos.txt", "a+") as f:#opens userinfos file as "f" and closes once finished
   with open("quizzes.txt", "a+") as fil:
      listofinfos = ["surname", "yeargroup"]#list with information apart from name and age

      if True:#will always run
         name = input("Enter your name:")
         age = input("Enter your age:")
         username = name[:3]+age#shortens name variable to first 3 letters and concatenates with age

      if str(username) in fi.read():
         hasAccount = True
         print("found username")
      else:
         hasAccount = False
         print("notfound")

0 个答案:

没有答案