使用文本文件创建登录系统

时间:2020-01-07 21:01:59

标签: python python-3.x

强文本我正在使用文本文件为python 3.7上的基于文本的简单游戏创建日志记录系统:

#puts information from a text file into a list so it can be compared to users inputs
logininfo = []
for line in open('user input.txt'):
    separator = ':'
    line = line.split(separator)
    for value in line:
        logininfo.append(value)
#To see whats inside the list of 'logininfo'        
print (logininfo)
#To separate it in the output screen, makes it easier too read
print("##########################")

username = str(input("Please enter your username: "))
password = str(input("Please enter your password: "))

#variable 'z' can be named anything
z = 0
#loops until it finds username in the database or goes through each data
while z < len(logininfo):
  if username == str(logininfo[z]):
    print ("Username exist")
    #variable 'g' can be named anything or could: z = z+1
    #one index higher than the usernames index (in the database) is always the corresponding password
    g = z + 1
    #puts data in new variable so we can remove the gaps it comes with it
    passwordshouldequal = str(logininfo[g])
    #Removes any spaces
    passwordshouldequal.replace(" ", "")
    #Checks information in the variable
    print (passwordshouldequal)
    if password == passwordshouldequal:
      print("Entered")
      exit()
    else:
      print ("password is wrong")
      #so it does not exit the loop
      exit()
  z = z + 1

#if the username does not exist 
print ("Error or username does not exist")

预期结果以“ Entered”结尾。实际结果以“ password is error”结尾。谁能帮我,谢谢!

编辑:人们问我的“用户输入”文本文件中的内容是什么,所以我给文本文件和输出屏幕拍了张照片。也谢谢你,我感谢你们所有人“用户输入”(注册用户的用户名和密码)和输出屏幕的图片:https://www.reddit.com/user/PlayableWolf/comments/eliq7y/stack_overflow/?utm_medium=android_app&utm_source=share

编辑#2 :删除了结尾的else位,因为我忘记了事先删除(当我修改代码时)

编辑#3 :特别感谢帮助我解决问题的 Michael Richardson 。还要特别感谢 nakE ,他超越了我并帮助我改善了代码。最后,感谢所有对我的问题发表评论的人,您的每一项评论都已被阅读并引起关注。因此,再次感谢您!

2 个答案:

答案 0 :(得分:0)

passwordshouldequal.replace(" ", "")的结果未存储。您需要将该行替换为:

passwordshouldequal = passwordshouldequal.replace(" ", "")

这可能仍然会失败,因为最后一个用户名/密码可能包含换行符(\ n)。我将其替换为以下内容:

passwordshouldequal = passwordshouldequal.replace(" ", "").replace("\n", "")

或更干净的方式:

passwordshouldequal = passwordshouldequal.strip()

答案 1 :(得分:0)

首先,我建议使用with打开文件,这样该文件将自动关闭,而您不必在最后关闭文件。从字符串中删除空格的一种更简便的方法是使用strip方法,strip方法有3种类型,一种是从左侧删除(lstrip)另一个是从右侧(rstrip)移出的(strip)。

with open('user input.txt') as f:
    for line in f:
        # perform things with the file
        # the file will closed automatically

还有一件事,到底谁是else条件?并且您的if条件甚至不在正确的行中。

您应该仔细检查代码,稍作休息,想一想要实现的目标,不是吗。