【问题标题】:How to check text file for usernames and passwords如何检查文本文件中的用户名和密码
【发布时间】:2018-03-26 02:58:54
【问题描述】:

我正在编写一个程序,该程序需要用户注册并使用帐户登录。我让程序让用户制作他们的用户名和密码,这些用户名和密码保存在外部文本文件(accountfile.txt)中,但是当涉及到登录时,我不知道如何让程序检查用户输入的内容存在于文本文件中。

这就是我的代码的样子:

def main():
    register()

def register():
    username = input("Please input the first 2 letters of your first name and your birth year ")
    password = input("Please input your desired password ")
    file = open("accountfile.txt","a")
    file.write(username)
    file.write(" ")
    file.write(password)
    file.close()
    login()

def login():
    check = open("accountfile.txt","r")
    username = input("Please enter your username")
    password = input("Please enter your password")

从现在开始我不知道该怎么做。

另外,这是注册帐户在文本文件中的样子:

Ha2001 examplepassword

【问题讨论】:

  • 这似乎是this question 的一个几乎重复的问题。一旦你有了这条线,就使用 split 来分隔这两个字段。我建议使用制表符而不是空格作为分隔符。
  • 您需要决定登录功能应该做什么。如果登录成功,也许您想返回TrueFalse 无论如何...您应该知道。
  • 您需要读取文件check,将每一行拆分成单独的单词,并将其与输入的用户名和密码进行比较。逐行继续,直到到达文件末尾或找到匹配的用户名。
  • 为什么需要存储密码?
  • 我希望这是一个学校作业,而不是一个“真正的”用户帐户系统。将密码存储在纯文本平面文件中是一个可怕的想法。

标签: python


【解决方案1】:

打开文件后,您可以使用readlines() 将文本读入用户名/密码对列表。由于您使用空格分隔用户名和密码,因此每一对都是类似于'Na19XX myPassword' 的字符串,您可以使用split() 将其拆分为两个字符串的列表。从那里,检查用户名和密码是否与用户输入匹配。如果您希望随着 TXT 文件的增长而出现多个用户,则需要在每个用户名/密码对之后添加一个换行符。

def register():
    username = input("Please input the first 2 letters of your first name and your birth year ")
    password = input("Please input your desired password ")
    file = open("accountfile.txt","a")
    file.write(username)
    file.write(" ")
    file.write(password)
    file.write("\n")
    file.close()
    if login():
        print("You are now logged in...")
    else:
        print("You aren't logged in!")

def login():
    username = input("Please enter your username")
    password = input("Please enter your password")  
    for line in open("accountfile.txt","r").readlines(): # Read the lines
        login_info = line.split() # Split on the space, and store the results in a list of two strings
        if username == login_info[0] and password == login_info[1]:
            print("Correct credentials!")
            return True
    print("Incorrect credentials.")
    return False

【讨论】:

  • 您的解决方案似乎有效,但仅适用于文本文件中添加的第一个帐户,我需要为多个帐户进行此操作。
  • 啊,如果是这种情况,那么您必须在每个用户名/密码组合之后插入一个换行符 ('\n')。我在上面编辑了我的答案,现在应该随着 txt 文件的增长而工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2016-09-24
  • 2017-11-29
  • 1970-01-01
相关资源
最近更新 更多