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

2024-10-01 07:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

strong text我正在使用一个文本文件为基于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:特别感谢迈克尔·理查森,他帮助我解决了我的问题。也特别感谢纳克,他超越了我,帮助我改进了我的代码。最后感谢所有对我的问题发表评论的人,你的每一条评论都已被阅读并铭记在心。因此,再一次在,谢谢你曾经一次


Tags: theinsolineusernameitpasswordbe
2条回答

首先,我建议使用with打开文件,这样文件将自动关闭,而不是在最后关闭文件。从字符串中删除空格的另一种更简单的方法是使用strip方法,有3种类型的strip方法,一种是从左侧(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条件甚至不在正确的行中

你应该仔细检查你的代码,休息一下想想你想要实现什么,不是这样的

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

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

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

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

或者更干净的方式:

passwordshouldequal = passwordshouldequal.strip()

相关问题 更多 >