如何知道何时到达文本文件的底部

2024-03-29 06:47:56 发布

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

所以我有一个文本文件,里面有我程序用户的详细信息。你知道吗

在我的程序中,我有一个从这个文本文件中检索数据的登录系统,但我不知道如何判断何时到达它的末尾。你知道吗

文本文件中的数据示例如下所示:

Bob, Bob15, football, 15

我的代码如下:

username = input("Enter username: ")
password = input("Enter password: ")

file = open("userDetails.txt", "r")
match = False
while match == False:
    finished = False
    while finished == False:
        for each in file:
            each = each.split(", ")
            realUser = each[1]
            realPass = each[2]
            if realUser == username and realPass == password:
                match = True
                finished = True
                print("match")
            elif each == "":
                finished = False
                username = input("Re-enter username: ")
                password = input("Re-enter password: ")
                match = False
            else:
                finished = False

我不确定的部分是elif each == "":部分。你知道吗

有什么想法吗?你知道吗


Tags: 数据程序falseinputmatchusernamepasswordfile
2条回答

当循环结束到达文件结尾时,正确的代码为:

file = open("userDetails.txt", "r")
match = False
while match == False:
    for each in file:
        each = each.split(", ")
        realUser = each[1]
        realPass = each[2]
        if realUser == username and realPass == password:
            match = True
            print("match")
        elif each == "":
            username = input("Re-enter username: ")
            password = input("Re-enter password: ")
            match = False

考虑到这个问题,我相信在这里使用^{}子句是很理想的。
注意for循环的else子句在循环正常退出时执行,即没有遇到break语句。你知道吗

算法
1询问用户输入
2最初将标志match设置为False
三。在文件中搜索,直到找到匹配项。
4使用上下文管理器打开文件;确保操作后关闭文件。
5找到匹配项后,立即中断文件循环,同时将标志match设置为True
6如果找不到匹配项,请用户重新输入凭据并再次执行搜索操作。
7继续,直到找到匹配的。你知道吗

代码

username = input("Enter username: ")
password = input("Enter password: ")

match = False
while not match:
    with open("userDetails.txt", "r") as file:
        for line in file:
            user_data = line.split(",")
            real_user, real_pass = user_data[1].strip(), user_data[2].strip()
            if username == real_user and password == real_pass
                print('Match')
                match = True
                break
        else:
            username = input("Re-enter username: ")
            password = input("Re-enter password: ")

提示:您还可以尝试使用CSV模块读取Python中的数据文件。你知道吗

相关问题 更多 >