gpt4 book ai didi

python - 如何检查文本文件中的用户名和密码

转载 作者:行者123 更新时间:2023-12-01 02:31:51 24 4
gpt4 key购买 nike

我正在编写一个程序,需要用户注册并使用帐户登录。我让程序让用户输入用户名和密码,并将其保存在外部文本文件(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

关于python - 如何检查文本文件中的用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46738966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com