Python给出的列表超出了界限,但它在lis中同时显示了这两个元素

2024-10-06 12:37:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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()

Tags: 用户列表inputyourreturnmaindefusername
3条回答

根据account_information.txt中的内容,file.read可能不是您想要使用的函数。你知道吗

实际上,read将返回一个字符串,即文件中所有字符的列表。例如,如果你的用户名和密码分别在两行上

foo
H0weSomeP4ssworD

您可以改为使用^{}将文件解析为字符串列表,其中每个元素都是文件中的一行。你知道吗

如果您查看位于7.2.1. Methods of File Objects的python文档,您将看到

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string or bytes object

您将看到f.read()不是您要查找的函数。请尝试f.readlines()将内容放入行列表中。你知道吗

If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

您应该使用readline在列表中获取您的信息:

def authenticateUser(username, password):
    credentials = []
    with open("account_information.txt") as f:
        content = f.readlines()

根据您的描述,content[0]将是您的用户名,content2是您的密码。你知道吗

相关问题 更多 >