我正在编写一个程序,需要用户注册并使用帐户登录。我得到程序让用户使用他们的用户名和密码保存在外部文本文件(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
答案 0 :(得分:2)
打开文件后,您可以使用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