如何检查用户名和密码的文本文件
我正在编写一个程序,需要用户注册并使用帐户登录。我得到的程序让用户输入他们的用户名和密码,这些用户名和密码保存在外部文本文件(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
打开文件后,就可以使用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
您的解决方案似乎可行,但仅适用于文本文件中添加的第一个帐户,我需要为多个帐户进行此项工作。 – OSG
啊,如果是这样的话,那么你必须在每个用户名/密码组合后插入一个换行符(''\ n'')。我编辑了上面的答案,现在应该随着txt文件的增长而工作。 –
这似乎是一个近乎重复的问题[这个问题](https://stackoverflow.com/questions/1904394/read-only-the-first-line-of-a-file)。一旦你有线使用拆分来分离两个领域。我建议使用选项卡作为分隔符而不是空格。 –
你需要做一些关于什么登录功能应该做的决定。如果登录成功,或者你应该知道它,也许你想返回'True'或'False'。 – efkin
您需要阅读文件**检查**,将每行分成单独的单词,并将其与输入的用户名和密码进行比较。一行一行地继续,直到到达文件末尾或找到匹配的用户名。 – Prune