我正在尝试使用python编写一个简单的登录程序(对python来说还是相当新的),并且我将登录信息存储在一个文本文件中,供用户匹配,以便成功登录。每当我运行它时,它都会显示“list index out of range”,但我能够打印出列表中该元素的值,这就是我困惑的地方。我试图将文件中的第一行(用户名)和第二行(密码)添加到列表中,以便与用户为每个字段输入的值进行比较,但无法进行比较。你知道吗
def main():
username = getUsername()
password = getPassword()
authenticateUser(username, password)
def getUsername():
username = input("Please enter your username: ")
return username
def getPassword():
password = input("Please enter your password: ")
return password
def authenticateUser(username, password):
credentials = []
with open("account_information.txt") as f:
content = f.read()
credentials.append(content)
if(username == credentials[0] and password == credentials[1]):
print("Login Successful!")
else:
print("Login Failed")
main()
根据
account_information.txt
中的内容,file.read
可能不是您想要使用的函数。你知道吗实际上,
read
将返回一个字符串,即文件中所有字符的列表。例如,如果你的用户名和密码分别在两行上您可以改为使用^{} 将文件解析为字符串列表,其中每个元素都是文件中的一行。你知道吗
如果您查看位于7.2.1. Methods of File Objects的python文档,您将看到
您将看到f.read()不是您要查找的函数。请尝试f.readlines()将内容放入行列表中。你知道吗
您应该使用readline在列表中获取您的信息:
根据您的描述,content[0]将是您的用户名,content2是您的密码。你知道吗
相关问题 更多 >
编程相关推荐